reactjs - setState 没有被触发
问题描述
我有以下代码
setTimeout(() => {
this.setState({loading: true});
}, 0);
axos.post("....")
setState 由于某种原因没有被触发。有人可以帮忙吗?
这是代码
submit(ev) {
ev.preventDefault();
setTimeout(() => {
this.setState({loading: true});
}, 0);
const {email, password} = ev.target.elements;
app.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);
// As httpOnly cookies are to be used, do not persist any state client side.
app.auth().signInWithEmailAndPassword(email, password).then(user => {
// Get the user's ID token as it is needed to exchange for a session cookie.
app.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({loading: true});
return user.getIdToken().then(idToken => {
// Session login endpoint is queried and the session cookie is set.
// CSRF protection should be taken into account.
const csrfToken = Utils.getCookie('csrfToken');
return this.postIdTokenToSessionLogin('/auth/session-login', idToken, csrfToken, "auth");
});
} else {
this.setState({error: "There was an error", loading: false});
}
});
}).catch(error => {
this.setState({error: error.message, loading: false});
})
}
解决方案
使用时,class methods
我们应该首先使用bind
它们constructor
。这与this
javascript 中的工作方式有关。this
从内部访问时,submit
它实际上是指submit
而不是您的Component
. 要么bind
这样
class Foo extends React.Component{
constructor(props){
super(props)
this.submit = this.submit.bind(this)
}
submit(e){
//now this refers to Foo's instance
}
}
或者你可以使用arrow functions
which has alexical this
class Foo extends React.Component{
submit = e =>{
//here this already refers to Foo's instance
}
}
推荐阅读
- bi-publisher - 如何在 BI Publisher 中添加复选框?
- javascript - 返回总和为给定值的所有子集(子集和问题)
- python - Django - 通用 ModelAdmin 定义
- android - 在 Hexagon DSP 上运行 Tensorflow Lite 演示模型
- python - Pyspark:如何从 HDFS 访问 XML 文件并使用 Pyspark/Python 读取 XML 文件
- azure - Azure AKS 网络分析 - 这些请求来自 Kubernetes 集群的何处?
- r-markdown - R Markdown - 并排定位表和绘图
- python - python fbprophet 中的 plot_components 返回重复的图
- amazon-web-services - 适用于 Docker 映像的带有 CodeDeploy 的 AWS CD
- django - 如何在 python django last v 中从 Url 获取 id?