Как правильно использовать параметр состояния в выборке URL? - PullRequest
0 голосов
/ 21 сентября 2018

Здравствуйте. У меня проблема с установкой переменной состояния в параметре url.Я пробовал несколько примеров, которые я нашел в Интернете, но никто не работает для меня.

Я пробовал это:

  constructor(props) {
    super(props);
    this.state = {
      channelId: []
    };
  }
     componentDidMount() {
          this.setState({ channelId: '1ae2275e-2ca2-42cb-be13-e97b59fbae13' });
        }
    componentWillMount() {
        fetch(
          `http://localhost:8080/api/channel/${this.state.channelId}`)
    .then...

И это:

  constructor(props) {
    super(props);
    this.state = {
      channelId: []
    };
 componentDidMount() {
      this.setState({ channelId: '1ae2275e-2ca2-42cb-be13-e97b59fbae13' });
    }
componentWillMount() {
    fetch(
      `http://localhost:8080/api/channel/'+this.state.channelId)
.then...

Ни один изони устанавливают значение в URL.Может кто-нибудь подскажет, что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 21 сентября 2018

Итак, первым делом нужно установить channelId в строку, а не в массив.

constructor(props) {
    super(props);
    this.state = {
      channelId: ''
     }
Позвольте мне спросить, почему вы хотите использовать componentWillMount ... Из моего опыта иногда добавляется жизненный цикл, который не всегда полезен.Вы пробовали

constructor(props) {
    super(props);
    this.state = {
      channelId: ''
    };
    
    componentDidMount() {
       this.getChannelId()
    }
    
    getChannelId() {
         this.setState({
            channelId: '1ae2275e-2ca2-42cb-be13-e97b59fbae13'
        });
        return fetch( `http://localhost:8080/api/channel/${this.state.channelId}`)
            .then(res => {
             // your code
             })
    }

?

Я использовал «похожий» подход для моего приложения:

import React, { Component } from 'react';
import { connect} from 'react-redux';
import { API_BASE_URL } from '../config';
import { Weekday, Weekendday } from './Day';
import './Availability.css';

const currentUserId = localStorage.getItem("id");

export class Availability extends Component {
    constructor(props) {
        super(props);
        
        this.state = {
            availability: {},
            loading: false,
            error: null
        };
    }

    componentDidMount() {
        this.loadAvailability()
    }


    loadAvailability() {
        this.setState({
            loading: true
        });
        return fetch(`${API_BASE_URL}/employee/${currentUserId}/availability`)
            .then(res => {
                if (!res.ok) {
                    return Promise.reject(res.statusText);
                }
                return res.json();
            })
            .then(availability => {
                console.log(availability)
                this.setState({
                    availability,
                    loading: false
                })
            })
            .catch(err => {
                this.setState({
                    error: 'Could not load availability list',
                    load: false
                })
                console.log(this.state.error, err)
            })
        }
        
        ...

Кроме того, вы не против поделиться остальным кодом для этого компонента, чтобы мы могли видеть, когда вам нужно еще одно изменение состояния?Спасибо!

0 голосов
/ 21 сентября 2018

componentWillMount вызывается перед componentDidMount -> поэтому в componentWillMount this.state.channelId = []

Я думаю, вам следует установить состояние channelId в ComponentWillMount и вызвать api в componentDidMount

constructor(props) {
    super(props);
    this.state = {
      channelId: ''
    };
 componentWillMount() {
      this.setState({ channelId: '1ae2275e-2ca2-42cb-be13-e97b59fbae13' });
    }
componentDidMount() {
    fetch(
      `http://localhost:8080/api/channel/'+this.state.channelId)
.then...

И с реакцией 16, реакция не рекомендует использовать componentWillMount в новом коде (Подробности: https://reactjs.org/docs/react-component.html#unsafe_componentwillmount)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...