我有一个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; } }
您的问题是,在成功获取之前tables,您的组件是使用state.tablesis 呈现的undefined。
tables
state.tables
undefined
首先,最佳实践是使用选择器而不是json路径(如)state.tables,selectors.js使用reselectlib 放在单独的文件中,如下所示:
selectors.js
reselect
import { createSelector } from 'reselect'; const tablesSelector = state => state.tables; export default { tablesSelector, }
其次,你需要添加减速机,让我们假设,FETCH_ALL_TABLES用行动combineReducers从reduxlib和最重要的初始化tables与阵列[]之前的动作被分派,从而被定义如下:
FETCH_ALL_TABLES
combineReducers
redux
[]
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可能需要将其更新为:
index.js
import selector from './selector'; ... function mapStateToProps(state) { return { tables: selector.tablesSelector(state), } }