React js mapStateToProps 触发 Uncaught TypeError:无法读取未定义的属性“map”

2023-12-10

我有一个 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: Cannot read property 'map' of undefined..

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

提前致谢..

--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;
   }
 }

你的问题是在成功获取之前tables,你的组件被渲染为state.tables is undefined.

首先,最佳实践是使用选择器而不是 json 路径,例如state.tables, 处于单独的selectors.js文件使用reselect库如下:

import { createSelector } from 'reselect';

const tablesSelector = state => state.tables;

export default {
  tablesSelector,
}

其次,您需要添加减速器,让我们假设,FETCH_ALL_TABLES行动使用combineReducers from reduxlib 和最重要的是初始化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),
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React js mapStateToProps 触发 Uncaught TypeError:无法读取未定义的属性“map” 的相关文章

随机推荐