【问题标题】:Why isn't my dispatch working? React Redux为什么我的调度不起作用?反应还原
【发布时间】:2019-06-04 21:09:03
【问题描述】:

我正在尝试使用 redux 商店更改我的 firebase 用户名。

我有一个注册表单,它接收输入的电子邮件、密码和用户名,然后表单使用电子邮件和密码创建一个 firebase 帐户,然后我使用 firebase 的 updateProfile 更新 displayName。看到这个

那是我的 redux reducer:

case "CHANGE_USERNAME":
      const currentUser = firebase.auth().currentUser;

      currentUser.updateProfile({ displayName: state.user.displayName });

      return { ...state.user, displayName: action.payload };

这是商店:

const initialState = {
  logged: null,
  user: {}
};

这是我的注册表的一部分:

firebase
        .auth()
        .createUserWithEmailAndPassword(this.state.email, this.state.password)
        .then(() => {
          this.props.dispatch({
            type: "CHANGE_USERNAME",
            payload: { ...this.state.username }
          });

          alert("Account created!");
        })
        .catch(error => {
          // Handling errors
          var errorCode = error.code;
          var errorMessage = error.message;
          alert(errorCode);
        });

为什么用户名没有改变?

【问题讨论】:

  • 这些警报alert("Account created!"); alert(errorCode); 是否有效?如果不是这个函数createUserWithEmailAndPassword 不返回Promise
  • 是的,我收到了 Account created!,不好的是承诺不会改变我的 Redux 存储

标签: javascript reactjs firebase redux firebase-authentication


【解决方案1】:

你没有从你的承诺中回报任何东西。假设createUserWithEmailAndPassword 返回一个承诺,并且响应包含一个username 字段,您希望将response.username 分派给您的reducer。

    .then((response) => {
      this.props.dispatch({
        type: "CHANGE_USERNAME",
        payload: { response.username }
      });

      alert("Account created!");
    })

在你的 reducer 中,你想添加新的 username 状态。比如:

return { ...this.state, username: payload }

【讨论】:

  • 这是不可能的,因为我没有收到来自 firebase 承诺的用户名,我的用户名处于组件的状态
  • 兄弟,我认为问题不是形式。看,我试过这样做: case "CHANGE_USERNAME": alert(action.payload);常量 currentUser = firebase.auth().currentUser; currentUser.updateProfile({ displayName: state.user.displayName });返回 { ...state.user, displayName: action.payload };我收到了我的用户名
【解决方案2】:

谢谢大家,我已经解决了这个问题:

case "CHANGE_USERNAME": {
      const currentUser = firebase.auth().currentUser;

      currentUser.updateProfile({ displayName: action.payload });

      return {
        ...state,
        user: { ...currentUser.providerData[0] }
      };
    }

在我的减速器上:

this.props.dispatch({
      type: "CHANGE_USERNAME",
      payload: this.state.displayName
    });

感谢我的派遣!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 2021-07-05
    • 2016-12-06
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    相关资源
    最近更新 更多