如何在Redux中更新状态后触发回调? [英] How to trigger off callback after updating state in 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中做的那样? / p>
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 (中间件将调度承诺的已解析值)
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屋!