谁能帮我用useEffect()重写这段代码?



代码如下:对于功能组件的使用,我还是个新手。

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

要将这个类组件转换为功能组件,您将需要useState()钩子用于错误的状态变量,useHistory()钩子用于history,useEffect()钩子用于主逻辑。

  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附加一个返回回调,以分离任何侦听器,或者在组件卸载时进行清理,如这里所述。

最新更新