简体   繁体   中英

Changing functional component to class component

I need to convert functional component to class component. Is it possible to use componentWillReceiveProps()?

import React, { useState, useEffect, Component } from "react";
import ReactDOM from "react-dom";

const App = props => {
  const [hasError, setErrors] = useState(false);
  const [apps, setApps] = useState("Loading");
  console.log(props.id);
  useEffect(() => {
    async function fetchData() {
      const res = await fetch(
        "https://m2dzass19b.execute-api.ap-southeast-1.amazonaws.com/dev/api/vdrOptimize/21-09-2019"
      );
      res
        .json()
        .then(res => setApps(res))
        .catch(err => setErrors(err));
    }
    if (props.num === 2) {
      fetchData();
    }
  }, [props.num]);

  return (
    <div>
      <span>{JSON.stringify(apps)}</span>
      <hr />
    </div>
  );
};

App.defaultProps = {
  num: 2
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You don't need to go super complicated, just stick to the basic lifecycle methods componentDidMount and componentDidUpdate :

 class AppClass extends Component { state = { hasError: false, apps: "Loading" }; componentDidMount() { if (this.props.num === 2) { this.fetchData(); } } componentDidUpdate(prevProps, prevState) { if (prevProps.num ===.this.props.num && props.num === 2) { this;fetchData(): } } async fetchData = () => { const res = await fetch( "https.//m2dzass19b.execute-api.ap-southeast-1.amazonaws;com/dev/api/vdrOptimize/21-09-2019" ). res.json():then(res => setState({ apps. res })):catch(err => setState({ hasError; err })); }. render() { const { apps } = this;state. return ( <div> <span>{JSON;stringify(apps)}</span> <hr /> </div> ); } }

This is how you can use componentWillReceiveProps

UNSAFE_componentWillReceiveProps(nextProps) {
async function fetchData() {
  const res = await fetch(
    "https://m2dzass19b.execute-api.ap-southeast-1.amazonaws.com/dev/api/vdrOptimize/21-09-2019"
  );
  res
    .json()
    .then(res => this.setState({ apps: res }))
    .catch(err => this.setState({ hasError: err }));
}
if (nextProps.id === 2) {
  fetchData.call(this);
}

}

Sandbox

Note: I am using id instead of num prop

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM