redux getState() doesn't return the updated state

扶醉桌前 提交于 2019-12-06 12:22:14

In order to use getState() in action file, you need to use it from store directly, rather you can get it as the second parameter to the inner function along with dispatch when using redux-thunk

export function testFunc(data) {
  return (dispatch, getState) => {
    dispatch(test(data))
    console.log('GLOBAL STATE IS :', getState())
  };
}

also your updated state will not be seen right after you dispatch the action since redux-state update happens asynchronously. You should rather check it in the componentDidUpdate function of the component where you are using the state.

Also, in order to get the updated state using store.getState() you need to subscribe to the state change like

// Every time the state changes, log it
// Note that subscribe() returns a function for unregistering the listener
const unsubscribe = store.subscribe(() =>
  console.log(store.getState())
)

and you can unsubscribe by calling

unsubscribe()

You may read more about it here

However when you use connect, you don't need to use store.getState() in the component, you can use mapStateToProps function to get the state values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!