【问题标题】:redux getState() doesn't return the updated stateredux getState() 不返回更新的状态
【发布时间】:2018-09-28 06:25:33
【问题描述】:

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

我使用 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);

【问题讨论】:

  • 你在哪里使用getState,你能在你看到这个问题的地方显示一个示例代码sn-p
  • 在上面的sn-p中没有看到你使用getState
  • 在 Page01.js
  • 具体在哪里,不在您提到的代码中
  • 对不起,我的意思是在 dispatch 之后就在 action.js 中

标签: javascript reactjs react-native redux getstate


【解决方案1】:

为了在action文件中使用getState(),你需要直接从store中使用它,而不是你可以在使用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函数来获取状态值。

【讨论】:

  • 哥们,我也试过componentDidUpdate,但问题依然存在!
  • unsubscribe() 返回未定义。我可以在哪里使用它?
  • 你不需要获取它的返回值,同样使用react,你不会使用store.subscribe而是连接
  • 谢谢你,你帮助找出了正确的方法。欣赏
  • @MrxRinc ,很高兴能帮上忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2019-08-06
相关资源
最近更新 更多