簡體   English   中英

如何在 React 中將經典組件轉換為功能組件

[英]How to convert classical component to functional component in React

請建議如何使用react js在功能組件中編寫constructor函數......因為我計划將類組件轉換為功能組件......任何人都可以幫忙

import React, { Component } from "react";
class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: []
    };
  }
  componentDidMount() {
    axios
      .get("https://www.example.com/users/id")
      .then(response => {
        this.setState({ descriptions: response.data });
        // console.log(response.data)
      })
      .catch(error => {
        console.log(error);
      });
  }
  render() {
    const { users } = this.state;
    return <div>Data</div>;
  }
}
export default Example;

為了在功能組件中使用狀態或生命周期方法,您應該使用 React Hooks

import React, { useState, useEffect } from 'react';

const Example =() => {
 const [users, setUsers] = useState([])
 useEffect(()=> {
    axios.get("https://www.example.com/users/id")
            .then(response => {
               // use setState hook here
                // console.log(response.data)
            })
            .catch(error => {
                console.log(error)
            })
 }, [])   

 return (
            <div>
              Data
            </div>
         )
}
export default Example

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM