这是在Submit上运行的功能:
signup(user = {}) {
this.setState({loading: true});
axios.post( '/users.json', { user })
.then(response => {
this.props.propagateSignIn(response.data)
this.setState({
error: null,
newUserEmail: this.email.current.value,
signedUp: true,
loading: false
}, console.log(this.state.signedUp, this.state.loading));
})
.catch(error => {
if( error.response ){
this.setState({
error: error.response.data,
loading: false
});
}
})
}
除此以外,所有内容均可运行:
this.setState({
error: null,
newUserEmail: this.email.current.value,
signedUp: true,
loading: false
}, console.log(this.state.signedUp, this.state.loading));
如果我在其后放置console.log()
,它也不会运行。
为什么状态不更新?
此处仅供参考,当this.props.propagateSignIn(response.data)
运行时在父组件中调用的函数:
propagateSignIn(user) {
this.getUser()
}
getUser(history = undefined) {
axios.get("/users/get_current_user", {})
.then(response => {
if (response.data.user) {
console.log('getUser:', response)
this.setState({isReady: true,
...response.data});
} else {
console.log("pas d'utilisateur connecté.")
this.setState({
user: null,
isReady: true
});
}
})
}
答案 0 :(得分:0)
好吧,实际上,您可以尝试用一个函数包装console.log,因为您需要提供一个回调,而不是“值”。因此,代码可能类似于:
this.setState({
error: null,
newUserEmail: this.email.current.value,
signedUp: true,
loading: false
}, () => console.log(this.state.signedUp, this.state.loading));
})
通常,不将回调放置到setState上被认为是最佳做法,您应该在生命周期方法内进行回调逻辑,例如在componentDidUpdate()
答案 1 :(得分:0)
在创建引用时,请确保引用了正确的组件。就我而言,this.email.current.value,
实际上是指另一个组件的输入,因为我将Component拆分为多个组件并且忘记更改某些引用。