【问题标题】:React/Redux: TypeError: Cannot read property 'target' of undefinedReact/Redux:TypeError:无法读取未定义的属性“目标”
【发布时间】:2018-08-29 20:06:27
【问题描述】:

我正在尝试使用某个用户(firstNamelastNameemail)的已编辑字段来更新我的状态(用户列表)。这个想法是每当用户更改表单中输入的值时,都会触发创建者操作以使用新值更新状态中的用户对象。以下是我的代码:

在我的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()),
});

为了测试我的代码,我编辑了表单,并在onValueChange() actionCreator 代码中收到此错误TypeError: Cannot read property 'target' of undefined。我不知道如何传递/捕获event(因为我正在尝试“还原”this

【问题讨论】:

    标签: javascript reactjs forms redux react-redux


    【解决方案1】:

    你没有将事件传递给你的减速器

    const mapDispatchToProps = dispatch => ({
      // some stuff
      onValueChange: (event) => dispatch(actionCreators.onValueChange(event)),
    });
    

    要获得更完整的答案...当您使用输入值时,只需传递事件即可。只要 mapDispatchToProps 在其中也有值,它就应该一直到你的 action/reducer。

    <input onChange={e=>this.props.onValueChange(e)} />

    【讨论】:

    • 请注意,mapDispatch 的用法可以通过使用“对象速记”将动作创建者的对象直接传递给connect 来简化。在这种情况下,它可能是export default connect(mapState, actionCreators)(MyComponent)
    • 通过的时候没有解决问题。感谢您的更正。
    • @oculti 在调用中添加事件后,动作中的事件仍未定义?您如何处理输入的 onChange?
    猜你喜欢
    • 2019-07-22
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多