简体   繁体   English

如何在 React 中为嵌套的 object 设置状态?

[英]How do I setState for a nested object in React?

I'm learning react by building a weather api.我正在通过构建天气 api 来学习反应。 I make an API call and store it in state.我进行了 API 调用并将其存储在 state 中。

  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
            });
        })
    }

When I pass this down as props, I get no data?当我将其作为道具传递时,我没有得到任何数据?

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

Use spread syntax to copy the entire previous object and then override some of its keys.使用扩展语法复制整个之前的 object,然后覆盖它的一些键。 You should also use the form of setState that takes a function because you want to reference the previous value of state.forecasts :您还应该使用采用 function 的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,
                },
            }));
        })

or you may want entirely new objects to wipe out the previous error state:或者您可能希望全新的对象消除之前的错误 state:

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

you are not passing the state correctly, you need to pass the state without quotation marks您没有正确通过 state,您需要通过不带引号的 state

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

should be like this:应该是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM