Redux 不会立即更新状态 [英] Redux does not update state immediately

查看:47
本文介绍了Redux 不会立即更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Redux 有问题,更可能不是问题而是误会.如果我确实在一个函数中调度并在 store 中写入一个新值,那么我无法立即从 store 中获取该函数的新值.

示例:

 testFunc = () =>{console.log('in func: before', this.props.count);//状态存储this.props.onButtonIncrementClick();//在商店中发送一个新状态console.log('in func: after', this.props.count);//获取旧的状态存储};

实例:

我怀疑这与异步有关,因为如果我将状态包装在 setTimeout() 中,则会出现一个新状态.

我很高兴听到有关为什么以及如何将值写入商店并立即从中读取的解释.

解决方案

setState 不是同步的,无论是你还是 Redux 更新它.

正如你所说,这是一种误解.当您直接更新它时,您可以提供要执行的回调,例如,

setState({ foo }, () => somethingWith(this.state));

(注意组件在回调之前已经重新渲染.)

如果您有需要在外部"状态更新(例如 Redux)之后运行的逻辑,则有 componentDidUpdate,但它也可能表明存在架构问题.

I have a problem with Redux, even more likely not a problem but a misunderstanding. If I do dispatch in a function and write a new value in the store then I can not immediately get into this function a new value from the store.

Example:

    testFunc = () => {
        console.log('in func: before', this.props.count);   //state store
        this.props.onButtonIncrementClick();                //dispatch a new state in the store
        console.log('in func: after', this.props.count);    //get the old state store
    };

Live example: https://codesandbox.io/s/yk1jzjv6l1

I suspect this is related to asynchrony since if I wrap the state in setTimeout() a new state comes.

I would be glad to hear an explanation of why and how you can write values ​​to the store and immediately read them from it.

解决方案

setState is not synchronous, whether it's you or Redux updating it.

This is a misunderstanding, as you say. When you're updating it directly you may supply a callback to be executed, e.g.,

setState({ foo }, () => somethingWith(this.state));

(Noting that the component has been re-rendered before the callback.)

If you have logic you need to run after an "external" state update (e.g., Redux) then there's componentDidUpdate, but it may also indicate an architectural issue.

这篇关于Redux 不会立即更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆