首页 > 解决方案 > 如何将当前用户 ID 分配给 React/Redux 中新创建的对象

问题描述

如何将当前用户的 id 分配给新创建的对象?我已经测试了服务器,它似乎在后端按我的意图工作,所以它一定是我的 React/Redux 流程的问题。

我目前正在表单上的提交处理程序中分配 userId,然后将其传递给操作和减速器。我在这里复制了我的代码以进行澄清。

在创建新对象时提交处理程序

  handleOnSubmit = event => {
    event.preventDefault();
    let newTeam = Object.assign({}, this.props.teamFormData, {
      author: this.props.auth.user.userId
    });
    this.props.createTeam(newTeam);
  };


行动

export const createTeam = team => {
  return dispatch => {
    return fetch(`${API_URL}/teams`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(team)
    })
      .then(response => response.json())
      .then(team => {
        dispatch(addTeam(team));
        dispatch(resetTeamForm());
      })
      .catch(error => console.log(error));
  };
};

减速器

    case "CREATE_TEAM_SUCCESS":
      return state.concat(action.teams);

在这个流程的某个地方,我从 React 组件开始为 userId 分配的对象失败了。我应该考虑以不同的方式做这件事吗?任何帮助将不胜感激。

标签: javascriptreactjsreduxreact-redux

解决方案


推荐阅读