【问题标题】:Could anybody please help me to rewrite this code using useEffect()?有人可以帮我用useEffect()重写这段代码吗?
【发布时间】:2021-09-24 13:58:43
【问题描述】:

这是代码。我对使用功能组件还是很陌生。

componentWillReceiveProps(nextProps) {
  if (nextProps.auth.isAuthenticated) {
    this.props.history.push("/dashboard");
  }

  if (nextProps.errors) {
    this.setState({
      errors: nextProps.errors,
    });
  }
}

【问题讨论】:

  • 你想达到什么目的?而且既然你用的是this.,那么它是一个类还是一个函数式组件?
  • 我们需要一个完全可重现的例子。还请说明您遇到了什么错误
  • 它最初是使用类组件编写的。但现在我正在尝试将其转换为功能组件。我正在尝试让用户登录到他们的帐户。这对他们进行身份验证以查看他们的详细信息在数据库中是否正确。如果正确,请将他们引导至他们的仪表板。
  • @jonathan Alfaro。我本身没有收到错误。我只是想知道如何重写它。
  • stackoverflow 中有一个策略。我们不会为您编写代码。我们只在您遇到麻烦时为您提供帮助。所以我们需要看看你已经尝试过什么。您需要提供一个完全可重现的示例以及当前结果和期望的结果

标签: node.js reactjs redux react-hooks


【解决方案1】:

要将这个类组件转换成函数式组件,你需要useState()钩子用于错误的状态变量,useHistory()用于historyuseEffect()用于主逻辑。

  1. 获取道具并提取所需数据:

     const {auth, errors} = nextProps; //Destructuring the object
    
  2. 为错误声明状态变量:

     //assuming its an array, setting empty array as default/initial value
     const [localErrors, setLocalErrors] = useState([]);
    
  3. 声明历史变量以推送/弹出页面:

     const history = useHistory();
    
  4. 最后,声明useEffect():

     //Adding auth and errors as dependencies to listen for changes
     //and run this code whenever any change occurs.
     //Remove them if useEffect should only be run first time
     useEffect(() => {
       if (auth.isAuthenticated) {
         history.push("/dashboard"); //changing page
       }
       if (errors) {
         setLocalErrors(errors); //updating state
       }
     }, [
     auth,
     errors
     ]); //Adding dependencies as an array
    

可选:您可以将返回回调附加到useEffect 以分离任何侦听器或在组件卸载时进行清理,如here 所述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-14
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多