【发布时间】:2019-08-13 15:30:09
【问题描述】:
redux 存储的状态正在改变,但无法让 object.map 函数重新渲染新状态。收到以下错误:“TypeError: Cannot read property 'map' of undefined”
确认actions.js中的数据正确,确认reducer.js中的数据正确,确认state.PrepInfos中的状态变化正确。
表格:
class PrepInfos extends Component {
render(){
const{ PrepInfos } = this.props;
return(
<Form>
{PrepInfos.map(prepInfo => <PrepInfo key={prepInfo.id} id={prepInfo.id} type={prepInfo.type} quantity={prepInfo.quantity} description={prepInfo.description} />)}
</Form>
);
}
}
const mapStateToProps = state => ({
PrepInfos: state.recipeForm.PrepInfos.PrepInfos,
});
const mapDispatchToProps = (dispatch) => bindActionCreators({
}, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(PrepInfos);
动作:
export const H_CHANGE = 'H_CHANGE';
export function hChange(event) {
const form = ({
value: event.target.value,
name: event.target.name,
id: event.target.id,
});
return ({
type: 'H_CHANGE',
data: form,
});
}
减速机:
import { H_CHANGE } from './PrepInfo/actions';
const initialState = {
PrepInfos: [{id:0, type:"makes", quantity:30, description:"slices"}, {id:1, type:"chill", quantity:15, description:"minutes"}],
};
export default function(state = initialState, action){
const { type, data } = action;
switch(type) {
case H_CHANGE:
return state.PrepInfos.map(prepInfo => {
if (prepInfo.id == data.id) {
return {...prepInfo, [data.name]: data.value}
};
return prepInfo;
});
default:
return state;
}
}
更正减速器:
return Object.assign({}, state, {
PrepInfos: state.PrepInfos.map(prepInfo => {
if (prepInfo.id == data.id) {
return {...prepInfo, [data.name]: data.value}
};
return Object.assign({}, prepInfo, {});
})
})
期望重新渲染新状态,而不是得到 TypeError: Cannot read property 'map' of undefined
【问题讨论】:
-
PrepInfos是如何进入props的?您要么缺少connect函数,要么需要显示更多代码 -
@EricHasselbring 刚刚添加了连接代码
标签: reactjs redux rendering reduce