在 Redux 中更新状态后如何触发关闭回调? [英] How to trigger off callback after updating state in Redux?

查看:22
本文介绍了在 Redux 中更新状态后如何触发关闭回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React 中,状态不会立即更新,因此我们可以在 setState(state, callback) 中使用回调.但是如何在 Redux 中做到这一点?

In React, state is not be updated instantly, so we can use callback in setState(state, callback). But how to do it in Redux?

在调用this.props.dispatch(updateState(key, value))之后,我需要立即对更新的状态做一些事情.

After calling the this.props.dispatch(updateState(key, value)), I need to do something with the updated state immediately.

有什么方法可以像我在 React 中所做的那样使用最新状态调用回调吗?

Is there any way I can call a callback with the latest state like what I do in React?

推荐答案

应该更新组件以接收新的道具.

有多种方法可以实现您的目标:

there are ways to achieve your goal:

1.componentDidUpdate 检查值是否改变,然后做一些事情..

1. componentDidUpdate check if value is changed, then do something..

 componentDidUpdate(prevProps){
     if(prevProps.value !== this.props.value){ alert(prevProps.value) }
  }

2.redux-promise(中间件会分发promise的解析值)

2. redux-promise ( middleware will dispatch the resolved value of the promise)

export const updateState = (key, value)=>
Promise.resolve({
  type:'UPDATE_STATE',
  key, value
})

然后在组件中

this.props.dispatch(updateState(key, value)).then(()=>{
   alert(this.props.value)
})

2.redux-thunk

export const updateState = (key, value) => dispatch => {
  dispatch({
    type: 'UPDATE_STATE',
    key,
    value,
  });
  return Promise.resolve();
};

然后在组件中

this.props.dispatch(updateState(key, value)).then(()=>{
   alert(this.props.value)
})

这篇关于在 Redux 中更新状态后如何触发关闭回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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