简体   繁体   English

ReactJs setState 回调不起作用

[英]ReactJs setState callback not working

I have a strange behavior with the setState callback, hopefully somebody can help.我对 setState 回调有一个奇怪的行为,希望有人可以提供帮助。 The callback just isn't fired.回调只是没有被触发。

Here is what I do:这是我所做的:

 this.setState( (prevState, props) => { return { first: obj, questions: [] } }, this.changeStateCb );

For some reason the changeStateCb function is never being called.出于某种原因,从未调用 changeStateCb 函数。 Same problem when I change it to:当我将其更改为时同样的问题:

 this.setState( (prevState, props) => { return { first: obj, questions: [] } }, () => console.log(this.state) );

I just updated from v15.x to 16.2.0我刚刚从 v15.x 更新到 16.2.0

Do you have a demo?你有演示吗? I just put up a simple working example , and it seems to run just fine under React 16.2.0 .我只是提出了一个简单的工作示例,它似乎在 React 16.2.0下运行得很好。 Do note though that the optional callback should be used sparingly .请注意,应谨慎使用可选回调。 As the docs mention, it will be executed once setState is completed and the component is re-rendered.正如文档中提到的,一旦setState完成并重新渲染组件,它将被执行。 So, a better place to do the logic in this.changeStateCb would be inside componentDidUpdate .因此,在this.changeStateCb执行逻辑的更好位置是在componentDidUpdate内部。

I just had the same issue happen to me.我刚刚遇到了同样的问题。 A simple console.log('test') in the callback wouldn't even run.回调中的简单console.log('test')甚至不会运行。 It turns out I had to delete my /dist folder in the build directory.事实证明,我必须删除构建目录中的 /dist 文件夹。 I am using Type Script and webpack and upgraded from a .net core template.我正在使用 Type Script 和 webpack,并从 .net 核心模板升级。

Have the same issue.有同样的问题。 The callback is not invoked.不调用回调。 I traced it to React min code and the function to enqueueSetState does not accept the callback even though it is passed in from internal React code...so code explains why it is not called.我将它追踪到 React 最小代码,即使它是从内部 React 代码传入的,enqueueSetState 的函数也不接受回调......所以代码解释了为什么不调用它。 But this used to work just fine in React 15.x - what's going on...I am trying React 16.8.4但这曾经在 React 15.x 中工作得很好 - 发生了什么......我正在尝试 React 16.8.4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM