我目前正在嘗試教自己做出反應。我遇到了這種奇怪的行為,無法解釋發生了什么,所以我希望能得到一些答案。
在下面的代碼片段中。我有一個index最初設定為0. 當我單擊按鈕時,我希望handleClick()更新index. 但是,它并沒有像我期望的那樣做。
const { useState } = React;
const Home = () => {
let names = ["Hello", "World"];
let index = 0;
const [name, setName] = useState(names[index]);
const handleClick = () => {
console.log(`Output: ${name}`);
console.log(`Index = ${index}`);
index = (index 1)%2;
setName(names[index]);
}
return (
<div className="Home">
<button onClick={handleClick}>Click</button>
</div>
);
}
ReactDOM.render(<Home />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
我希望console.log輸出如下:
Output: Hello
Index = 0
Output: World
Index = 1
Output: Hello
Index = 0
Output: World
Index = 1
...
相反,我得到的是:
Output: Hello
Index = 0
Output: World
Index = 0
Output: World
Index = 1
Output: Hello
Index = 0
...
有人可以解釋這里發生了什么嗎?
uj5u.com熱心網友回復:
當使用 setState 方法更新狀態變數時,組件會重新渲染。在您的代碼中,索引變數不是狀態變數,因此每當 Home 組件重新渲染時,索引變數都會被初始化為 0。
您可以將索引更改為狀態變數,或者您也可以使用 ref,如果您要在重新渲染中保持其狀態。
uj5u.com熱心網友回復:
您應該考慮將索引移動到狀態并將名稱移動到道具。前者將糾正組件的行為,正如您正在尋找的那樣,后者將使組件更具可重用性。
const { useState } = React;
const Home = ({names}) => {
const [index, setIndex] = useState(0);
const name = names[index];
const handleClick = () => {
console.log(`Output: ${name}`);
console.log(`Index = ${index}`);
setIndex((index 1)%2);
}
return (
<div className="Home">
<button onClick={handleClick}>Click</button>
</div>
);
}
ReactDOM.render(<Home names={["Hello", "World"]} />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
uj5u.com熱心網友回復:
而不僅僅是let index = 0
每次運行時重新初始化為 0setName您需要未重新初始化的內容,如下所示
//on your imports
import {useRef} from 'react'
//inside you component
const index = useRef(0);
//on updating it
index.current = (index.current 1)%2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/457635.html
標籤:javascript 反应
上一篇:設計模式之狀態模式
