簡體   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