React / Redux使用store从另一个组件获取状态

时间:2018-07-25 20:29:00

标签: javascript reactjs react-native redux react-redux

我刚刚开始使用Redux,因为我的应用程序将状态传递给其他组件变得很复杂。尝试将数据检索到其他组件时遇到错误。

我想将状态传递给另一个组件,但出现此错误:

enter image description here

store.js

import {createStore} from 'redux';

const initialState = {
  regionId: 0
};
const reducer = (state = initialState, action) => {

  if(action.type === "REGIONAL_ID") {
     return {
        regionId: action.regionId
      };
    }
    return state;
}
const store = createStore(reducer);
store.subscribe(() => {
  console.log(store.getState().regionId)
})

export default store;

在我的Network.js组件中,我正在调用

const REGION_ID = store.subscribe(() => {
    return store.getState().regionId;
})
console.log(REGION_ID);

我尝试了以下操作,但这也给了我一个错误。非常感谢!

const REGION_ID = return store.getState().regionId;

1 个答案:

答案 0 :(得分:1)

这不是错误。 store.subscribe()方法返回一个unsubscribe方法,而console.log()显示此方法的实现:

const REGION_ID = store.subscribe(() => {
    return store.getState().regionId; // this is isn't returned to REGION_ID
})
console.log(REGION_ID); // REGION_ID contains the unsubscribe method

如果要使用regiondId,请从州获得,将代码放入订阅回调中:

tore.subscribe(() => {
    const REGION_ID = store.getState().regionId;
    console.log(REGION_ID );
})

此行const REGION_ID = return store.getState().regionId;产生错误,因为you can't return outside of a function