gpt4 book ai didi

javascript - 状态已保存,但表示未保存

转载 作者:行者123 更新时间:2023-11-30 12:08:37 25 4
gpt4 key购买 nike

我有一个类似于默认 ReactJS 教程的 React 应用程序。

我在提交表单后调用的组件中有一个函数,如下所示:

getInitialState: function () {
return {
name: "First Product",
showOwner: true
}
},

handleFormSubmit: function (name) {
console.log(name); //Returns "Hello world"
console.log(this.state.name); // Returns "First Product"

this.setState({name: name});
this.setState({showOwner: false});

console.log(this.state.name); // Returns "First Product" still
}

出于某种原因,当我在 React 开发人员工具中检查它时,它显示 this.state.name IS 被设置为新值,但是当我在 console.log 中显示时它仍然显示显示第一个值而不是“Hello World”?

最佳答案

来自 https://facebook.github.io/react/docs/component-api.html 处的文档:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

还有:

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.

因此,根据文档,您希望代码中包含以下内容:

handleFormSubmit: function (name) {
console.log(name); //Returns "Hello world"
console.log(this.state.name); // Returns "First Product"

this.setState({
name: name,
showOwner: false
}, function() {
// Should return "Hello world" after the state has been set.
console.log(this.state.name);
}.bind(this));

// Returns "First Product" still, since setState is not synchronous
console.log(this.state.name);
}

我不知道 React,但文档就是这么说的,我没有理由相信那行不通。

关于javascript - 状态已保存,但表示未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34475865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com