Javascript 如何等待数据被提取并使用redux更新状态

Javascript 如何等待数据被提取并使用redux更新状态,javascript,reactjs,redux,Javascript,Reactjs,Redux,我想知道如何等待数据被提取,然后更新我正在使用的redux的本地组件状态 这是我的组件 class Users extends Component { state = { localUsers: [] } componentDidMount() { this.props.fetchUsers(this.props.selectedGroup); /* this.setState({localUsers

我想知道如何等待数据被提取,然后更新我正在使用的redux的本地组件状态

这是我的组件


class Users extends Component {


    state = {
        localUsers: []
    }

    componentDidMount() {
        this.props.fetchUsers(this.props.selectedGroup);
        /*
        this.setState({localUsers: this.state.localUsers.concat(this.props.users)})
        if I update the state here this is asyncronous code
         so it will be update before the data is fetched */
    }

    render() {
        const users = this.state.users.map((user, key) => {
            return (<div key={key} className="card mt-2">
                <div className="card-body">
                    {user}
                </div>
            </div>)

        })

        return (
            <div data-spy="scroll" data-target="#navbar-example3" data-offset="0">
                {users}
            </div>

        )

    }


}


const mapStateToProps = state => {
    return {
        users: state.users.data,
    }
}

const mapDispatchToProps = dispatch => {
    return {
        fetchUsers: () =>
            dispatch(fetchUsers())
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Users);

如何在完成提取后更新状态this.props.fetchUsers已完成

您可能希望使用componentDidUpdate,当组件从Redux接收更新的props时会触发该更新

componentDidMount() {
    this.props.fetchUsers(this.props.selectedGroup); <-- dispatch redux action
}

//triggered when getting updated props
componentDidUpdate(prevProps){
    if(prevProps.users !== this.props.users){
       this.setState({
          localUsers: this.props.users
       })
    }
}

雷杜·图恩?或者在fetchUsers返回有用信息时简单地发送?另外,从外观上看,您有一个在代码中注释的承诺。使用.then或async/await,如果我返回一个承诺,那么我不尊重redux结构。操作文件处理所有承诺,并使用特定的操作类型调用reducer谢谢!这正是我要找的!在旧版本中,ComponentReceiveProps的作用相同。