钩子等效于componentWilLReceiveProps以更新状态

时间:2019-05-24 03:41:39

标签: reactjs

所以我有一个组件,可以在道具更改时有条件地更新状态。如果当前状态的CurrentPage不等于下一个道具的CurrentPage,我将使用下一个道具的CurrentPage更新状态:

public componentWillReceiveProps(nextProps) {
    if (this.state.CurrentPage !== nextProps.CurrentPage) {
        this.setState({ CurrentPage: nextProps.CurrentPage });
    }
}

我在重构组件的过程中确实使用了钩子。组件首次加载时,我为CurrentPage设置了useState挂钩:

const [currentPage, setCurrentPage] = useState(props.CurrentPage?props.CurrentPage:1);

在这种情况下,等效于componentWillReceiveProps逻辑的钩子是什么?谢谢!

2 个答案:

答案 0 :(得分:2)

为此目的使用“ useEffect”挂钩。

 useEffect(() => {
if(props.yourproperty){ 
//execute your code.
}
   console.log('property changed', props.yourproperty);
 },[props.yourproperty])

仅在props.property更改的情况下才调用此属性,因此无需检查旧的props。

UseEffect Hook docs

答案 1 :(得分:1)

您将利用useEffect()钩子。有关原因的解释,请阅读我的指南以了解该钩子以及如何利用它:React Hooks Guide - useEffect(给它一些加载时间,codesandbox有点慢)。

您的示例有点武断,因为您的props已经包含当前页面,但是,这是一个有效的示例...

工作示例(用于更新其他组件状态的道具):

Edit Simple Page Monitor


组件/导航

import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";
import { Link, withRouter } from "react-router-dom";

const style = {
  marginRight: 5
};

const Navigation = ({ location: { pathname }, children }) => {
  // initializing "currentPage" with the current "pathname" prop
  // initializing "setPage" function to update "currentPage"
  const [currentPage, setPage] = useState(pathname);

  // utilizing useEffect to keep track of "pathname" changes 
  // that, upon change, will update the "currentPage" state
  useEffect(() => {
    setPage(pathname);
  }, [pathname]);

  return (
    <div className="container">
      <div className="nav">
        <Link style={style} to="/">
          Home
        </Link>
        <Link style={style} to="/page1">
          Page 1
        </Link>
        <Link style={style} to="/page2">
          Page 2
        </Link>
      </div>
      <div className="page">
        <p>
          (current page: <strong>{currentPage}</strong> )
        </p>
      </div>
      {children}
    </div>
  );
};

Navigation.propTypes = {
  pathname: PropTypes.string
};

export default withRouter(Navigation);