如何在React中为嵌套对象设置状态?

时间:2020-07-04 15:02:16

标签: javascript reactjs

我正在学习通过构建天气API来做出反应。我进行API调用并将其存储在状态中。

  state = {
        forecasts: {
            error: null,
            isLoaded: false,
            forecasts: []
        }
    }

    componentDidMount() {
        const endpoint = `http://dataservice.accuweather.com/forecasts/v1/daily/5day/207931?apikey=KEY&language=en&details=true&metric=true`;
        fetch(endpoint)
        .then(res => res.json())
        .then((result) => {
            this.setState({
                'forecasts.isLoaded': true,
                'forecasts.forecasts': result.DailyForecasts,
            });
        },
        (error) => {
            this.setState({
                'forecasts.isLoaded': true,
                'forecasts.error': error
            });
        })
    }

当我将其作为道具传递时,我没有数据吗?

<WeatherOverview weather={this.state.forecasts}/>

2 个答案:

答案 0 :(得分:2)

使用spread syntax复制整个先前的对象,然后覆盖其某些键。您还应该使用带有函数的setState形式,因为您要引用state.forecasts的先前值:

.then((result) => {
            this.setState(state => ({
                forecasts: {
                    ...state.forecasts,
                    isLoaded: true,
                    forecasts: result.DailyForecasts,
                },
            }));
        },
        (error) => {
            this.setState(state => ({
                forecasts: {
                    ...state.forecasts,
                    isLoaded: true,
                    error: error,
                },
            }));
        })

或者您可能希望全新的对象清除以前的错误状态:

.then((result) => {
            this.setState({
                forecasts: {
                    error: null,
                    isLoaded: true,
                    forecasts: result.DailyForecasts,
                },
            });
        },
        (error) => {
            this.setState(state => ({
                forecasts: {
                    forecasts: [],
                    isLoaded: true,
                    error: error,
                },
            }));
        })

答案 1 :(得分:-2)

您未正确传递状态,您需要在不带引号的情况下传递状态

this.setState({
 'forecasts.isLoaded': true,
 'forecasts.forecasts': result.DailyForecasts,
});

应该是这样的:

    this.setState({
     forecasts: {
      ...state.forecasts,
      isLoaded:true,
      forecasts:result.DailyForecasts},
   });