无法在回调函数中更新组件的状态 [英] Can't update a component's state inside a callback function

查看:28
本文介绍了无法在回调函数中更新组件的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

constructor(props) {
    this.state = {contents: []};
}

componentDidMount() {
    var self = this;
    console.log('> Manage mounted');
    ServerService.getServers(
        Parse, 
        self.props.parentState.state.activeAccount,
        (error, results) => {
            if (error) {
                throw new Error(error); 
            }

            this.setState((prevState, props) => ({
              contents: results 
            }));
        }
    );
}

你好,我上面有这个代码.我有一个名为管理和服务器的组件.现在,从安装 Manage 组件开始,我想通过 ServerService.getServers() 填充它的 this.state.contents.该实用程序返回一个 results,它是一个来自回调函数的数组.但是,状态没有进入.这是从回调函数中更新组件状态的正确方法吗?

Hi there, I have this code above. I have a component named Manage and Servers. Now, from the time the Manage component is mounted, I wanted to populate it's this.state.contents by means of ServerService.getServers(). The utility returns a results, which is an array from a callback function. Though, the state is not getting in. Is this the correct way of updating a component's state from the within a callback function?

此外,我将上述状态传递给名为 MainContent 的子组件,例如<MainContent contents={this.state.contents}/>,并在组件挂载时将其作为道具观看

Furthermore, I am passing the said state to a child component named MainContent e.g. <MainContent contents={this.state.contents} />, and watching it as a props, when the component is mounted

componentDidMount() {
    console.log('> MainContent is mounted');
    console.log(this.props.contents);
}

问题是,来自 MainContent 组件的 this.props.contents 仍然是一个空白数组.我这样做的原因是因为我进一步使用了 contents 中的值,作为 MainContent 子组件的另一组 props.

The thing is, this.props.contents from MainContent component remains a blank array. The reason why I am doing this is because I have further usage of the value in contents, as another sets of props for MainContent child components.

推荐答案

您用来更新状态的方法在您尝试更新类似状态的场景中很有用

The approach that you are using to update the state is useful in a scenario when you are trying to update a state sort of like

    this.setState((prevState, props) => ({
          contents: [...prevState.content, props.content]
        }));

ie 使用之前的 state 以及 props 因为 this.props 和 this.state 可能会异步更新,你应该不要依赖它们的值来计算下一个状态.

i.e making use of the previous state as well as props because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

然而,您在函数内部使用 setState,因此 this 关键字在这里不会引用正确的内容,您也应该使用 self ,因为您正在更新具有不依赖于状态或道具的值的状态,因此您可以使用像

However you are using setState inside a function and hence this keyword here won't refer to the correct content, you should make use of self also since you are updating the state with a value that is not dependent on state or props and hence you can use the direct approach of updating a state like

self.setState({contents: results});

代码:

componentDidMount() {
    var self = this;
    console.log('> Manage mounted');
    ServerService.getServers(
        Parse, 
        self.props.parentState.state.activeAccount,
        (error, results) => {
            if (error) {
                throw new Error(error); 
            }

            self.setState({
              contents: results 
            });
        }
    );
}

至于在 MainContentcomponentDidMount 中获得一个空白数组,您将得到一个平淡的数组,因为 componentDidMount 仅在初始渲染时呈现,并且因为在初始渲染你的 this.state.contents 是一个空数组,你得到一个空值.

As far as getting a blank array in componentDidMount of MainContent is concerned, you will get a bland array because componentDidMount is rendered only on the initial render and since at initial render your this.state.contents is a blank array, you get a empty value.

将其更改为 componentWillReceiveProps

componentWillReceiveProps(nextProps) {
    console.log("Main content");
    console.log(nextProps.contents);

}

这篇关于无法在回调函数中更新组件的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆