如何在组件中触发Redux函数

时间:2019-10-22 14:05:59

标签: javascript reactjs redux react-redux antd

我有一个应该在提交时创建新用户的表单。在handleCreate上,我需要redux来触发addUser动作并更新状态,从而创建一个新用户,但是我似乎没有正确调用该动作。

action.js

 const addUser = payload => ({
    payload,
    type: ADD_USER,
});

reducer.js

const addUsers = (items, newItem) => {
    const { id } = newItem;
    items[id] = newItem;
    return { ...items };
};

       case ADD_USER: {
            const { users } = state;
            const { payload: { item } } = action;
            return {
                ...state,
                isUpdated: true,
                users: addUsers(users, item),
            };
        }

在组件中触发动作的功能

    handleCreate = () => {
        const { form } = this.formRef.props;
        const { addUser } = this.props.actions;
        form.validateFields((error, values) => {
            if (error) {
                return error;
            }
            form.resetFields();
            const user = {
                age: values.age,
                birthday: values[DATE_PICKER].format('YYYY-MM-DD'),
                firstName: values.firstName,
                hobby: values.hobby,
                id: uuid(),
                lastName: values.lastName,
            };
            addUser(user);
        });
    };

2 个答案:

答案 0 :(得分:2)

您遇到的问题是破坏播放负载,const { payload: { item } } = action;期望payload拥有密钥item

const action = {
  payload: {
    item: {
      a: "a",
      b: "b"
    }
  }
};

const {
  payload: { item }
} = action;

console.log(item)

const { payload: { item } } = action;替换为减速器中的

const { payload: item } = action;

答案 1 :(得分:2)

查看另一个答案的注释中链接的实际项目,我找到了问题的根源,您的ADD_USER的简化器必须为

    case ADD_USER: {
      const { users } = state;
      return {
        ...state,
        isUpdated: true,
        users: addUsers(users, action.payload)
      };
    }

在拥有const { payload: { item } } = action;之前,您曾期望动作对象被成形

{
   type: WHATEVER_TYPE,
   payload: { item: user }
},

但是动作实际上看起来像

{
   type: WHATEVER_TYPE,
   payload: user,
},