【问题标题】:componentWillReceiveProps to React hookscomponentWillReceiveProps 到 React 钩子
【发布时间】:2020-09-18 18:56:51
【问题描述】:

我想将基于类的组件更改为功能组件,我有

const initialState={

     displayName: "",
        email: "",
        password: "",
        confirmPassword: "",
        error: "",
    }


componentWillReceiveProps(nextProps,nextContext){
const userError=nextProps;
if(userError){
this.setState({error:userError.message});
}
}

我做选择器

export const selectUserError = createSelector(
  [selectUser],
  (user) => user.error
);





 {this.state.error ? (
        <SweetAlert
          show={this.state.error}
          type="warning"
          title="Something went wrong"
          text={this.props.userError}
          onConfirm={() => this.setState({ error: "" })}
        />
      ) : null}

然后我将 mapState 传递给 props。 有人可以帮忙吗?

【问题讨论】:

标签: reactjs react-redux react-hooks


【解决方案1】:

您可以简单地使用来自 props 的数据,而不是将 props 存储在 state 中

const {userError} = this.props;
...
 {userError && userError.message ? (
        <SweetAlert
          show={!!userError.message}
          type="warning"
          title="Something went wrong"
          text={userError.message}
          onConfirm={() => this.props.dispatch({ type: 'RESET_ERROR', error: "" })} // Dispatch and action here that updates state in store
        />
      ) : null}

【讨论】:

  • 但是 componentWillreceiveProps 仍然存在:/这就是我想要改变的
  • 不要更改它,您只需将其删除。如果可以直接从 props 推导出来,则不需要复制 props 来专门声明
  • 假设你的 mapStateToProps 就像const mapStateToProps = (state, props) =&gt; { return { userError: selectUserError(state, props) } },上面的代码可以工作。请注意您使用的是 props,而不是在 sweetalert 中的任何地方声明
  • this.props.dispatch 不是一个函数,它正在工作,但是当我在 sweetalert 窗口中单击“确定”时,我得到了这个
  • 你知道如何在 redux 中 dispatch 一个 action 并更新 user.error 状态吗?如果是这样,请按照此替换 onConfirm 操作。在上面的帖子中,调度是一个假人,用于通知需要调度一个 redux 操作
【解决方案2】:

感谢@shubham-khatri 的帮助,我解决了这个问题。 我在我的 user.types 中输入了 RESET_ERROR 类型,之后我进行了操作 reseterror。 在我的注册组件中调度,之后我可以在 onConfirm 方法中使用。 它工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2021-03-08
    • 1970-01-01
    • 2022-01-07
    • 2021-09-29
    • 2020-07-11
    • 2017-01-14
    相关资源
    最近更新 更多