redux getState() 没有 return 更新状态

redux getState() doesn't return the updated state

让我卡住了好几天的问题是,虽然我的 redux devtool 显示状态更新成功,没有任何类型的突变,并且视图组件重新渲染成功,但是当我调用 getState() 时,它总是 return初始状态,不关心更新状态!任何知道什么会导致这种情况的人请帮助我。

我使用 react-redux 和 redux-thunk

action.js

export function test(data) {
  return {
    type: 'TEST',
    data
  };
}

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

reducer.js

export default function peopleReducer(state = initialState, action) {
  switch (action.type) {
    case 'TEST':
      return {
        ...state,
        test: action.data
      }
    default:
      return state;
  }
}

Page01.js

componentDidUpdate(){
   console.log('get state = ', store.getState())
}

....

<TouchableHighlight 
   underlayColor={"#0e911b"}
   onPress={() => {
   this.props.testing('test contenttttt !!!!')            
    }}
 >
   <Text style={styles.title}>ACTION</Text>
</TouchableHighlight>



function mapStateToProps(state) {
  return {
    people: state.people,
    planets: state.planets,
    test: state.test
  };
}

function mapDispatchToProps(dispatch) {
  return { 
    getPeople: () => dispatch(getPeopleFromAPI()), 
    getPlanets: () => dispatch(getPlanetsFromAPI()), 
    testing: data => dispatch(testFunc(data)) };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

为了在 action 文件中使用 getState(),您需要直接从存储中使用它,而不是在使用 redux-thunk 时将其作为内部函数的第二个参数连同 dispatch 一起获取

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

此外,由于 redux-state 更新是异步发生的,因此在您发送操作后不会立即看到您的更新状态。您应该在使用状态的组件的 componentDidUpdate 函数中检查它。

此外,为了使用 store.getState() 获取更新状态,您需要订阅状态更改,例如

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

您可以 unsubscribe 通过调用

unsubscribe()

您可以阅读更多相关内容 here

但是当你使用connect时,你不需要在组件中使用store.getState(),你可以使用mapStateToProps函数来获取状态值。