redux存储的状态正在按需更改,但无法获取object.map函数来重新呈现新状态。收到以下错误:“ TypeError:无法读取未定义的属性'map'”
确认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:无法读取未定义的属性“ map”
答案 0 :(得分:0)
该错误是由化简器中的状态突变引起的
// this is mutating the PrepInfos property in state
return state.PrepInfos.map(prepInfo => {
if (prepInfo.id == data.id) {
return {...prepInfo, [data.name]: data.value}
};
return prepInfo;
});
// this is creating and returning a new obj for state and the PrepInfos key in state
return {
...state,
PrepInfos: state.PrepInfos.map(prepInfo => {
if (prepInfo.id == data.id) {
return {...prepInfo, [data.name]: data.value}
};
return prepInfo;
}