繁体   English   中英

React / Redux无法读取未定义的属性“ currentOpportunities”

[英]React/Redux cannot read property “currentOpportunities” of undefined

我的Redux mapStateToProps函数遇到麻烦,抛出一个错误,指出state.currentOpportunities未定义。 奇怪的是,只能在state._root.entries 1 .organization.currentOpportunity下访问,而不是在console.log时通过state.organization.currentOpportunity到达。主index.js文件

Console.log(状态)

App.js主文件

const initialState = {}
const history = createHistory();
const store = configureStore(initialState, history);
const MOUNT_NODE = document.getElementById('app');

const render = messages => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
      </LanguageProvider>
    </Provider>,
    MOUNT_NODE,
  );
};

OrganizationReducer.js

const initialState = {
    currentOpportunities: [],
    expiredOpportunities: []
};

export default function (state=initialState, action) {
    switch(action.type) {
        case FETCH_ORGANIZATION_OPPORTUNITIES:
            return {...state, data: action.payload}
        case FETCH_CURRENT_OPPORTUNITIES: 
            return{...state, currentOpportunities: action.payload}
        case FETCH_EXPIRED_OPPORTUNITIES: 
            return{...state, expiredOpportunities: action.payload}
        default:
            return state
    }
}

我的根减速器文件

export default function createReducer(injectedReducers) {
  return combineReducers({
    organization: organizationReducer,
    ...injectedReducers
  })
}

index.js文件

const mapStatetoProps = (state) => {
  console.log(state)
  return {
    currentOpportunities: state.organization.currentOpportunities,
    expiredOpportunities: state.organization.expiredOpportunities
  };
}

export default connect(mapStatetoProps, actions)(OpportunitiesPage);

有人知道这里会发生什么吗?

state.organization.currentOpportunity未定义,因为state是一个不变的映射,并且您尝试像访问对象一样访问其字段。 1个

您必须更新reducer逻辑以使用合并对象的不可变API, 例如

   case FETCH_ORGANIZATION_OPPORTUNITIES:
        return state.merge({data: action.payload})

或从不可变数据结构转换为可变的javascript对象。 例如

  stateObject = state.toJS()
  return {
      currentOpportunities: stateObject.organization.currentOpportunities,
      //...

由于它可能会导致跟踪某个对象的实例处于状态的麻烦,因此建议您在组件状态下坚持使用不可变数据结构或可变Javascript对象。

这是使用不可变地图API的mapStateToProps。 2

  return {
      currentOpportunities: state.getIn(['organization', 'currentOpportunities'])
      //...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM