我想知道如何等到提取数据后再更新本地组件状态(我正在使用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完成)之后,如何更新状态
答案 0 :(得分:1)
您想使用componentDidUpdate()
,当组件接收到更新的道具(您将从Redux获取)时触发。
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
})
}
}