簡體   English   中英

將 React Class 轉換為功能組件

[英]Convert React Class to a Functional Component

在我的舊存儲庫中,我使用了帶有以下 CruiseListHeader 組件代碼的 Class 組件作為示例(用於顯示 Cruise Buttons)。

    import React from 'react';
    import {getCruiseLines} from '../api/api'
    import ListofShips from './ListofShips'
    
    
    class CruiseListHeader extends React.Component {
        constructor(props)  {
            super(props)
    
            //setting intial state for Cruise Headings and initialize cruiseHeaders as an empty array
            this.state = {
                cruiseHeaders: []
            } 
            
            //binding methods for setting up Cruise Line Headings
            this.setUpCruiseLines = this.setUpCruiseLines.bind(this)
        }  
    
        componentDidMount() {
            console.log('cdm')
            this.setUpCruiseLines()
        }
    
        setUpCruiseLines()  {
            console.log('getcruiselines')
            getCruiseLines()
                .then(res   =>  {
    
                    this.setState({
                        cruiseHeaders: res
                    })
                })
        }
         
        render()    {
            return  (

            <React.Fragment>

                {/* There will be Headings for all the Cruise Lines. */}
                {/* Map the Cruiseline Headings for each Ship to display them on the page. I want to map ship, because I need each ship displayed in a List, when Cruise Line Heading is clicked. */}

            <div className = "cruiseContainer">

                {this.state.cruiseHeaders.map (ship =>  {
                
                    return (

                    <div key={ship.cruise_line}>

                        {/* ListofShips component needs cruise_line, because when user clicks on Cruise Line Heading button,
                            we need to fetch ships that belongs to that particular cruiseline. */}
                        {/* We need to render multiple ListofShips components, with one for each cruiseline */}
                        <ListofShips cruise_line={ship.cruise_line}></ListofShips>

                    </div>
                    )

                })}

            </div>      

            </React.Fragment> 
        )
    }
} 

export default CruiseListHeader

請注意,這都與下面顯示的 Cruise Lines 頁面相關,該頁面有一個主CruiseLines.jsx組件,其中導入了上面提到的 CruiselistHeader.jsx。

巡航線路頁面上的巡航按鈕

現在我想通過將此 React Class 組件轉換為功能組件來開始更改。

到目前為止,這就是我的 CruiseListHeader 作為功能組件。

請注意,ListofShips 現在在這個新存儲庫中稱為 ShipsList。

import React, { useEffect, useState} from 'react'
import {getCruiseLines } from '../api/api'
import ShipsList from './ShipsList'

function CruiseListHeader() {

    // Declare cruiseHeaders State variable 
    const [cruiseHeaders] = useState({
        
    })

    useEffect (() =>    {

    // Note: This was the original ComponentDidMount that took Binding this.setUpCruiseLines()
    // Now it is coming from the CruiseListHeader.js useEffect to the DOM    
    }
    )
    

    return  (
        <>
        <div>    
            <div key={ship.cruise_line}>
                <ShipsList cruise_line={ShipsList.cruise_line}></ShipsList>            
            </div>
        </div>    
        </>
    )
}

export default CruiseListHeader

我想了解的是,功能組件如何處理來自我的 api 的 state,我之前在 Class 組件中使用的綁定和映射?

如果有人對我如何處理這個問題有任何想法,那將是非常寶貴的幫助,謝謝。

您忽略了狀態的設置器,您的useState行應該是:

const [cruiseHeaders, setCruiseHeaders] = useState({});

然后您將使用該setCruiseHeaders函數來設置狀態:

useEffect (() => {
  getCruiseLines()
    .then(res => {
      setCruiseHeaders({
        cruiseHeaders: res
      })
    });
}, []); // Make sure to also pass an array here, or you'll be triggering this effect on every render

順便說一句,您可能打算將狀態值初始化為數組而不是對象:

const [cruiseHeaders, setCruiseHeaders] = useState([]);

由於原始代碼中的“巡航標題”數據是一個數組。

import React, { useEffect, useState} from 'react'
import {getCruiseLines } from '../api/api'
import ShipsList from './ShipsList'

function CruiseListHeader() {

    // Declare cruiseHeaders variable and set it's array using useState 
    const [cruiseHeaders, setCruiseHeaders] = useState([]);    
    
    // Note: This was the original ComponentDidMount that took Binding this.setUpCruiseLines()
    // Now it is coming from CruiseListHeader.jsx useEffect to the DOM    

    useEffect (() => {
        getCruiseLines()
          .then(res => {
            setCruiseHeaders({
              cruiseHeaders: res
            })
          });
      }, []); // Make sure to also pass an array here, or you'll be triggering this effect on every render

    return  (
        <>

        {/* <div className = "cruiseContainer"> I don't think I need this because I am using Tailwind CSS*/}
        {/* When I use Sass in my next final repo I may not need a div either */}

            {cruiseHeaders.map (ship => {

                // return  ( Do not need return here, I think

                    <div key = {ship.cruise_line}>

                        {/* ListofShips component needs cruise_line, because when user clicks on 
                        Cruise Line Heading button, we need to fetch ships that belongs to that particular 
                        cruiseline. */}
                        {/* We need to render multiple ShipsList components, with one for each cruiseline */}
                        <ShipsList cruise_line={ship.cruise_line}/>

                        {/* </ShipsList>  I think I don't I need this closing tag*/}
                    </div>

                // ) I think, I do not need return closing bracket here
            })}
        {/* </div> I think, I do not need closing div from cruiseContainer here*/}

        </>
    )
}

export default CruiseListHeader

暫無
暫無

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

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