首页 > 解决方案 > 在 React 中的函数内更新类的状态

问题描述

我正在尝试使用存储在变量中的对象数组来更新此类的状态childData。但是,当我使用setState({childData: childData)},并稍后通过调用使用它时this.state.childData,它是undefined,因此它永远不会使用信息更新状态。


class Users extends React.Component {
    state = {
        childData: ""
    }

   retrieve = () => {
       let childData;
       var leadsRef = database.ref('users');
       leadsRef.on('value', function(snapshot) {
           childData = snapshot.val();
           console.log(childData)
           this.setState({
               childData: childData
           })
       });
    }

    componentDidMount() {
        this.retrieve()
    }

    render() {
        return(
            <div>
            <h3>These are all the users in the app</h3>
            {console.log(this.state.childData)}
            </div>
        )
    }
}

export default Users

标签: javascriptreactjs

解决方案


你有几个问题正在发生。首先,您确实需要在回调函数中设置状态。但是,照原样,您会遇到无限循环。那是因为您不应该在render方法中执行异步功能。相反,请在componentDidMount方法中执行此操作,以便仅在组件安装时触发。

class Users extends React.Component {
    state = {
        childData: ""
    }

   retrieve = () => {
       let childData;
       var leadsRef = database.ref('users');
       leadsRef.on('value', snapshot => {
           childData = snapshot.val();
           console.log(childData)
           this.setState({
               childData: childData
           })
       });
    }

    componentDidMount() {
        this.retrieve()
    }

    render() {
        return(
            <div>
            <h3>These are all the users in the app</h3>
            {console.log(this.state.childData)}
            </div>
        )
    }
}

export default Users

推荐阅读