小编典典

反应js mapStateToProps触发未捕获的TypeError:无法读取未定义的属性'map'

reactjs

我有一个index.js,它呈现数据库中的所有表。

_renderAllTables() {
const { fetching } = this.props;

let content = false;

if(!fetching) {
  content = (
    <div className="tables-wrapper">
      {::this._renderTables(this.props.allTables)}
    </div>
    );
}

return (
  <section>
    <header className="view-header">
      <h3>All Tables</h3>
    </header>
    {content}
  </section>
);
}

_renderTables(tables) {

return tables.map((table) => {
  return <Table
            key={table.id}
            dispatch={this.props.dispatch}
            {...table} />;               
});
}

render() {
return (
  <div className="view-container tables index">
    {::this._renderAllTables()}
  </div>
  );
 }
}
const mapStateToProps = (state) => (
  state.tables);

export default connect(mapStateToProps)(HomeIndexView);

我将mapStateToProps从上面的代码更改为下面的代码。

 const mapStateToProps = (state) => ({
tables: state.tables,
currentOrder: state.currentOrder,
});

我更改代码的原因是我想使用currentOrder状态之一。我有一个状态,显示表是否忙。因此,为了使用它,我在mapStateToProps中添加了currentOrder。但是,它触发Uncaught
TypeError:无法读取未定义的属性“ map”。

如何使用其他组件的状态?有什么建议吗?

提前致谢..

--reducer.js

 const initialState = {
  allTables: [],
  showForm: false,
  fetching: true,
  formErrors: null,
   };


  export default function reducer(state = initialState, action = {}) {
   switch(action.type){
    case Constants.TABLES_FETCHING:
        return {...state, fetching: true};

    case Constants.TABLES_RECEIVED:
        return {...state, allTables: action.allTables, fetching: false};

    case Constants.TABLES_SHOW_FORM:
        return {...state, showForm: action.show};

    case Constants.TALBES_RESET:
        return initialState;

    case Constants.ORDERS_CREATE_ERROR:
        return { ...state, formErrors: action.errors };


    default:
        return state;
   }
 }

阅读 270

收藏
2020-07-22

共1个答案

小编典典

您的问题是,在成功获取之前tables,您的组件是使用state.tablesis 呈现的undefined

首先,最佳实践是使用选择器而不是json路径(如)state.tablesselectors.js使用reselectlib
放在单独的文件中,如下所示:

import { createSelector } from 'reselect';

const tablesSelector = state => state.tables;

export default {
  tablesSelector,
}

其次,你需要添加减速机,让我们假设,FETCH_ALL_TABLES用行动combineReducersreduxlib和最重要的初始化tables与阵列[]之前的动作被分派,从而被定义如下:

import {combineReducers} from 'redux';

function tables(state = [], {type, payload}) {
  switch (type) {
    case 'FETCH_ALL_TABLES':
      return [
        ...state,
        ...payload,
      ]
  }

  return state;
}


export default combineReducers({
  tables,
});

index.js可能需要将其更新为:

import selector from './selector';

...

function mapStateToProps(state) {
  return {
    tables: selector.tablesSelector(state),
  }
}
2020-07-22