reactjs - 状态不变
问题描述
我正在开发一个 react js 应用程序并做一些基本的事情,设置新值时状态似乎没有改变。这是代码:
pageChange = currentPage => {
const newState = Immutable.merge(this.state,
{
page: currentPage
},
{ deep: true });
this.setState(newState);
console.log(this.state); // the page property remains the same
console.log(newState); // the page property has the new value, the currentPage
this.openPreview();
}
在代码中,当前状态未被设置,但 newState 具有新值。为什么?
解决方案
您可以利用 setState() 的第二个参数:
pageChange = currentPage => {
...
this.setState(
newState,
() => this.openPreview() // This occurs -after- setState has finished
// ensuring openPreview() works as you expect
);
}
推荐阅读
- python - 无法使用 spyder(任何版本)导入 tensorflow 2.x:Tensorflow_core.estimator 问题
- reactjs - 在使用 three.js 渲染 3D 模型时,使用 Next.Js 与普通 React 相比有什么优势吗?
- terraform - 通过 ssh 密钥远程使用 Terraform 模块的 Teamcity 代理
- c++ - 如何在单独的 config.h 文件中声明全局变量
- windows - 获取挂起脚本的行号
- reactjs - useEffect exhaustive-deps 警告:这试图避免哪些可能的问题?
- angular - 错误:projects/custom-lib/src/lib/components/accordion/accordion.component.html:1:1 - 错误 NG8001:'ngb-accordion' 不是已知元素
- jaxb - JAXB 阻塞 UTF-16 XML
- apache-kafka - KTable 没有对具有相同键的传入记录进行重复数据删除
- javascript - 转换以将 API 数据发送到要在折线图中使用的其他组件