Redux状态更改后该怎么办?

时间:2020-02-05 07:56:33

标签: javascript reactjs react-native redux

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

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

我正在像下面这样的本地状态函数上做

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

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

2 个答案:

答案 0 :(得分:0)

您可以使用useEffect来检查更新的全局状态,并产生副作用,在您的情况下,这是调用takePic()

因此,假设您的Redux已connect加入了您的组件:

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

答案 1 :(得分:0)

您可以将

创建为异步操作
export const setCameraState = () => async (dispatch) => {
    // Write your action logic here
};

然后在通话时

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();
    }
}