當我運行該應用程序時,出現錯誤:「無法讀取屬性'forEach'未定義」在我的items
屬性上。調試後,我發現屬性項僅在組件內部未定義。 我已經在我的mapStateToProps函數和我的reducer中定義了items
。屬性在組件內部未定義 - React Redux
這是組件:
import React from 'react';
import ListItemCont from '../containers/list-item.js';
class ListComp extends React.Component {
constructor (props){
super(props);
}
render() {
let itemsComponents = [];
this.props.items.forEach((item) => {
itemsComponents.push(
<ListItemCont description={item.description}
header={item.header}>
</ListItemCont>)
});
return(
<ul>
{itemsComponents}
<button onClick={this.props.onAddClick()}></button>
<button onClick={this.props.onRemoveClick()}></button>
</ul>
)
}
}
export default ListComp;
這是我的容器:
import {addItem, removeItem} from '../actions/list.js';
import {connect} from 'react-redux';
import ListComp from '../components/list.jsx';
const mapStateToProps = (stateProps, ownProps) => {
return {
items: stateProps.items
}
};
const mapDispatchToProps = (dispatch) => {
return {
onAddClick:() => {
dispatch(addItem());
},
onRemoveClick: (item) => {
dispatch(removeItem(item));
}
}
};
const ListCont = connect(mapStateToProps, mapDispatchToProps)(ListComp);
export default ListCont;
這是我的減速器:
import {LIST_ACTIONS} from '../utilities/consts.js';
import {addItem, removeItem} from '../actions/list.js';
const initialState = {
items: []
};
export const listReducer = (state = initialState, action) => {
switch(action.type){
case LIST_ACTIONS.ADD_ITEM: {
return Object.assign({}, state, {items: [...items, action.item]});
}
case LIST_ACTIONS.REMOVE_ITEM: {
let itemIndex = state.item.indexOf(action.item);
return Object.assign({}, state, {items: [
...state.items.slice(0, itemIndex),
...state.items.slice(itemIndex + 1)
]});
}
default: {
return state;
}
}
};
缺少什麼我在這裏?我不知道爲什麼項目是未定義的。
我覺得應該是'stateProps.listReducer.items'您還需要指定減速。 –
@MayankShukla它仍然不起作用,它說我試圖更新渲染方法內部的狀態並導致無限循環中的重新渲染 –