React | 类组件转化成函数组件,steps

49 阅读1分钟

summary

  1. 修改 class 到 function 组件
  2. constructor 初始化变量换成 useState
  3. 修改 setState 函数
  4. 修改所有的 this.[变量]
  5. 修改所有的 this.[函数]
  6. componentDidUpdate
  7. componentDidMount
  8. componentWillUnmount

1. 修改 class 到 function 组件

before

class DashBoard extends React.Component {}

after

const DashBoard = (props) => {}

2. constructor 初始化变量换成 useState

before

  constructor(props) {
    super(props);
    this.state = {houseColor:"red",houseAttrs:{} };
  }

after

const [state,setState] = useState({houseColor:"red",houseAttrs:{} });

3. 修改 setState 函数

before

  this.setState({houseColor:"pink"});

after

 this.setState(prev => ({...prev,houseColor:"pink"}));

4. 修改所有的 this.[变量]

before

  this.isFullScreen = false;

after

// 如果有 赋值
const [isFullScreen,setIsFullScreen] = useState(false);
// 没有赋值
const isFullScreen = false

5. 修改所有的 this.[函数]

before

class DashBoard extends React.Component {
    getColor = () =>{}
    // this.getColor()
}

after

const DashBoard = (props) => {
    const getColor = () =>{}
    // getColor()
}

6. componentDidUpdate

after

useEffect(() =>{
    functions()
},[props])

7. componentDidMount

after

useEffect(() =>{
    functions()
},[])

7. componentWillUnmount

after

useEffect(() =>{
    return () =>{functions()}
},[])