如何防止組件在反應中重新渲染? (How to prevent component from re-rendering in react?)


問題描述

如何防止組件在反應中重新渲染? (How to prevent component from re‑rendering in react?)

內容組件,它將 API 作為來自另一個組件的參數。但是當它接受一個新的輸入並且 API 更新時,它會重新渲染(我認為是 twise)並且結果數組是空的。那就是問題所在。這是代碼。

    import React from 'react';
import  { useState,useEffect } from 'react';
import ReactDOM from 'react‑dom';

const Content=(api)=>{

  const [cities, setItems] = useState([]);

  const API=api;
  console.log(API);


  useEffect(() => {
  //  setItems([]);  //clearing cities array.deleting previuos data from the array
    fetch(API)
      .then(res => res.json(console.log(res)))
      .then(
        (result) => {
          console.log(cities)
          setItems(cities => cities.concat(result));

        },
      )
  },[API]);

  console.log(cities)

    return (
        <ul>
        {cities.map(citi => (
          <li key={citi.city.id}>
            The city is is{citi.city.id} 
            The city name is{citi.city.name}
            The temparature is {citi.list[0].main.temp}
          </li>
        ))}
      </ul>


    )
  }


export default Content;

第一個日誌返回一個空數組。但是第二個日誌正在返回具有正確結果的數組 這是控制台 輸出

如你所見,它渲染了兩次,最後一個數組是空的。所以我的問題是最終結果數組是一個空數組,即使 api 正在獲取數據。因為這個組件沒有返回任何東西。如何解決。輸出顯示數組是空的

please don'


參考解法

方法 1:

I am assuming that the API you have mentioned here is props and it should be props.api. The answer is using the api in the Content component after destructuring from props

import React from 'react';
import  { useState,useEffect } from 'react';
import ReactDOM from 'react‑dom';

const Content=({api})=>{

  const [cities, setItems] = useState([]);

  useEffect(() => {
    if(api){
        fetch(api)
           .then(res => res.json())
           .then(result => {
                // add some guarding condition here for result
                let updatedCities = cities.concat(result);
                setItems(updatedCities);
           })
    }
  },[api]);

  console.log(cities)

    return (
        <ul>
        {cities.map(citi => (
          <li key={citi.city.id}>
            The city is is{citi.city.id} 
            The city name is{citi.city.name}
            The temparature is {citi.list[0].main.temp}
          </li>
        ))}
      </ul>     
    )
  }
export default Content;

This would only re‑render when the API has changed.

(by aravinda nawarathnaErick)

參考文件

  1. How to prevent component from re‑rendering in react? (CC BY‑SA 2.5/3.0/4.0)

#react-hooks #javascript #reactjs






相關問題

使用反應鉤子useState更新功能的正確方法是什麼? (What is the correct way to use react hook useState update function?)

測試 react-redux useSelector (testing react-redux useSelector)

從深度嵌套的組件更新狀態而不重新渲染父組件 (Update state from deeply nested component without re-rendering parents)

React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))

類型“IntrinsicAttributes”(自定義掛鉤)上不存在 React 屬性 (React Property does not exist on type 'IntrinsicAttributes' (custom hook))

即使驗證要求無效,數據仍在發送,解決此問題的最佳方法是什麼? (Data is sending even if validation requirements are not valid, whats the best way to approach this?)

如何在使用狀態掛鉤更新狀態時覆蓋具有相同鍵的對象 (How can overwrite objects that have the same key in updating State with state hooks)

在 useEffect 中,調用更新時是否會更新所有變量? (In useEffect, do all variables get updated when an update is called?)

反應鉤子,不會將選中的屬性更改為複選框 (React hooks, does not change the checked property to checkbox)

在 reactJS 中動態設置圖像 src (Setting image src dynamically in reactJS)

如何防止組件在反應中重新渲染? (How to prevent component from re-rendering in react?)

使用 useEffect 和 setInterval 一個接一個地打印一個字母 (print one letter after the other with useEffect and setInterval)







留言討論