Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

javascript - How to trigger off callback after updating state in 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?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...