問題描述
如何防止組件在反應中重新渲染? (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 nawarathna、Erick)