【问题标题】:How to do something after Redux state changed?Redux 状态改变后怎么办?
【发布时间】:2020-02-05 07:56:33
【问题描述】:

我想在应用 Redux 状态后运行 takePic() 函数。假设如下代码:

this.props.setCameraState({
    foo: bar,
    foo2: bar
}).then(() => takePic());

我在本地状态函数上做这件事,如下所示:

this.setState({
    foo: bar,
    foo2: bar,
}, async () => takePic());

但我不知道如何在 Redux 上做到这一点。

【问题讨论】:

  • 你能做的是有一个变量来跟踪,就像你用装载机做的一样。一旦动作被调度,你将 loader 设置为 true,当它被获取时你可以设置为 false,如果为 false,你可以触发一个函数
  • 我考虑过这种方法。但是有更好的方法吗?
  • 嗯,我也必须检查一下,我赞成这个问题才能真正得到答案
  • 请为您认为有帮助的答案投票。 :)
  • UtkarshPramodGupta 谢谢 :)

标签: javascript reactjs react-native redux


【解决方案1】:

您可以使用useEffect 检查更新的全局状态,并执行副作用,在您的情况下调用takePic()。

所以,假设你的 redux 是 connected 到你的组件:

const MyComponent = ({ foo, foo2 }) => {
  useEffect(() => {
    takePic();
  }, [foo, bar]);
};

【讨论】:

    【解决方案2】:

    您可以将异步操作创建为

    export const setCameraState = () => async (dispatch) => {
        // Write your action logic here
    };
    

    然后在调用do的时候

    this.props.setCameraState({
        foo: bar,
        foo2: bar
    }).then(() => takePic());
    

    或者

    await this.props.setCameraState({
        foo: bar,
        foo2: bar
    });
    
    takePic();
    

    您可以尝试使用componentDidUpdate钩子的其他方式

    componentDidUpdate(prevProps) {
        if(prevProps.foo !== this.props.foo || prevProps.foo2 !== this.props.foo2) {
            takePic();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2019-01-30
      • 1970-01-01
      相关资源
      最近更新 更多