react js mapStateToProps触发器未捕获的TypeError:无法读取未定义的属性“map”

时间:2016-11-14 10:46:20

标签: reactjs redux

我有一个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;
   }
 }

2 个答案:

答案 0 :(得分:2)

您的问题是,在成功抓取tables之前,您的组件的呈现时state.tablesundefined

首先,最佳做法是使用选择器而不是像state.tables这样的json路径,使用selectors.js lib位于单独的reselect文件中,如下所示:

import { createSelector } from 'reselect';

const tablesSelector = state => state.tables;

export default {
  tablesSelector,
}

其次,您需要使用FETCH_ALL_TABLES lib中的combineReducers添加reducer,假设redux操作,最重要的是使用{{1}初始化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

答案 1 :(得分:0)

您应该始终检查是否定义了要映射的变量。

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