How to trigger off callback after updating state i

2019-01-13 17:18发布

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

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

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

4条回答
乱世女痞
2楼-- · 2019-01-13 17:56

You can use a thunk with a callback

myThunk = cb => dispatch =>
  myAsyncOp(...)
    .then(res => dispatch(res))
    .then(() => cb()) // Do whatever you want here.
    .catch(err => handleError(err))
查看更多
Explosion°爆炸
3楼-- · 2019-01-13 17:58

The most important point about React is one-way data flow. In your example that means, that dispatching an action and state change handling should be decoupled.

You shouldn't think like "I did A, now X becomes Y and I handle it", but "What do I do when X becomes Y", without any relation to A. Store state can be updated from mutiple sources, in addition to your component, Time Travel also can change state and it will not be passed through your A dispatch point.

Basically that means that you should use componentWillReceiveProps as it was proposed by @Utro

查看更多
叼着烟拽天下
4楼-- · 2019-01-13 17:59

You could use subscribe listener and it will be called when an action is dispatched. Inside the listener you will get the latest store data.

http://redux.js.org/docs/api/Store.html#subscribelistener

查看更多
对你真心纯属浪费
5楼-- · 2019-01-13 18:13

component should be updated to receive new props.

there are ways to achieve your goal:

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

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

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

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

then in component

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

then in component

this.props.dispatch(updateState(key, value)).then(()=>{
   alert(this.props.value)
})
查看更多
登录 后发表回答