redux getState() 不返回更新的状态

mrx*_*inc 8 javascript getstate reactjs react-native redux

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

我使用 react-redux 和 redux-thunk

动作.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() )
  };
}
Run Code Online (Sandbox Code Playgroud)

减速器.js

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

页面01.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);
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 8

为了getState()在动作文件中使用,你需要直接从 store 使用它,而不是你可以在使用时将它作为第二个参数与内部函数一起使用redux-thunk

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

由于 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())
)
Run Code Online (Sandbox Code Playgroud)

你可以unsubscribe打电话

unsubscribe()
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读更多关于它的信息

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