我正在尝试使用某个用户的编辑字段(firstName
,lastName
,email
)更新我的状态(用户列表)。这个想法是每当用户更改表单中输入的值时,触发创建者操作以使用新值更新处于该状态的用户对象。以下是我的代码:
在我的reducers.js
:
case actionCreators.changeUserValues.getType():
return {
...state,
usersList: [
...state.usersList.map((user) => {
if (user.username === action.payload.username) {
return {
...user,
[action.payload.name]: action.payload.value,
};
}
return user;
}),
],
editButtonDisabled: false,
submitButtonDisabled: true,
selectedUserProfile: {
userObject: {
...state.selectedUserProfile.userObject,
[action.payload.name]: action.payload.value,
},
},
};
在actionCreators.js
文件中:
const changeUserValues = createAction(CHANGE_USER_VALUES, userData => userData);
const onValueChange = event => (dispatch, getState) => {
const { value, name } = event.target;
const { username } = getState().selectedUserProfile.username;
return dispatch(changeUserValues({ name, value, username }));
};
在我的容器中:
const mapDispatchToProps = dispatch => ({
// some stuff
onValueChange: () => dispatch(actionCreators.onValueChange()),
});
为了测试我的代码,我编辑了表单,我在TypeError: Cannot read property 'target' of undefined
actionCreator代码中得到了这个错误onValueChange()
。我不知道如何过去/捕捉event
(因为我正在尝试'redux'this)
您没有将事件传递给减速机
const mapDispatchToProps = dispatch => ({
// some stuff
onValueChange: (event) => dispatch(actionCreators.onValueChange(event)),
});
有关更完整的答案...当您使用输入值时,只需传递事件即可。只要mapDispatchToProps中也有值,它应该一直到你的action / reducer。
<input onChange={e=>this.props.onValueChange(e)} />