const [countries,setCountries] = useState(["usa","china","russia"])
const [country,setCountry] = useState('uk")
現在,當我嘗試更新舊狀態時,反應行為不同
const updateCountries = () => {
setCountry(previous => {
console.log("I should be printed once and will be printed once")
return previous
})
setCountries(previous => {
console.log("I should be printed once but will be printed TWICE")
return previous.map(country => country);
})
}
當我試圖更新國家陣列的狀態時,反應執行了兩次 console.log?
注意:這個問題與陣列狀態無關,因為類似的東西在我的 react-native 應用程式的其他組件中運行良好,我試圖找出其他可能的原因。
uj5u.com熱心網友回復:
如果沒有完整的代碼,很難說 100%,但您的代碼似乎觸發了重新渲染,這就是 setCountries 運行兩次的原因。它不應該與陣列有關,而是與您運行事物的順序有關。
如果您將 setCountry 和 setCountries 放在 useEffect 之外,您很可能會觸發您不想要的無限重新渲染。
您可能想要的是類似于下面的代碼:
import React, { useState } from 'react';
function App() {
const [countries, setCountries] = useState(['usa','china','russia']);
const [country, setCountry] = useState('');
const handleClick = () => {
setCountries(previous => {
console.log("I should be printed once and I am printed once", previous);
const newArray = [...previous];
newArray.push(country);
return newArray;
});
}
return (
<div className="App">
<input type="text" onChange={(e) => setCountry(e.target.value)} value={country} />
<button onClick={handleClick}>Add Country</button>
<ul>
{countries && countries.map(c => <li key={c}>{c}</li>)}
</ul>
</div>
);
}
export default App;
uj5u.com熱心網友回復:
因為您的代碼導致 2 次重新渲染到您的組件。一個與 setCountry,第二個 - 與 setCountries。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405739.html
標籤:
