【问题标题】:Can't update a component's state inside a callback function无法在回调函数中更新组件的状态
【发布时间】:2017-02-13 06:24:44
【问题描述】:
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 and Servers 的组件。现在,从安装 Manage 组件开始,我想通过 ServerService.getServers() 填充它的 this.state.contents。该实用程序返回一个results,它是一个来自回调函数的数组。但是,状态没有进入。这是从回调函数中更新组件状态的正确方法吗?

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

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

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

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

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

    即使用之前的stateprops,因为this.props 和this.state 可能会异步更新,您不应依赖它们的值来计算下一个状态。

    但是,您在函数中使用 setState,因此此处的 this 关键字不会引用正确的内容,您也应该使用 self,因为您正在使用不依赖于的值更新状态状态或道具,因此您可以使用更新状态的直接方法,例如

    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 是一个空白数组,你得到一个空值。

    将其更改为componentWillReceiveProps

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

    【讨论】:

    • 嗨@Shubham,谢谢你的回答。抱歉,我还有其他问题要问。我在上面更新了我的问题。
    • @TeodyC.Seguin 更新了您进一步查询的答案
    • 谢谢@Shubham,这真的很有帮助。我现在得到填充的数组。
    • 太好了,很高兴能帮上忙
    猜你喜欢
    • 1970-01-01
    • 2020-09-12
    • 2021-08-24
    • 1970-01-01
    • 2019-10-31
    • 2023-01-30
    • 2022-12-09
    • 1970-01-01
    • 2020-11-26
    相关资源
    最近更新 更多