這是 CodeSandBox 鏈接:https ://codesandbox.io/s/stale-prop-one-g92sv ? file =/ src/App.js
我發現子組件在單擊兩次按鈕后不會顯示正確的計數器值,盡管計數器實際上是在遞增:
import "./styles.css";
import { useState } from "react";
const MyComponent = ({ value }) => {
const [counter] = useState(value);
return <span>{counter}</span>;
};
export default function App() {
const [counter, setCounter] = useState(0);
const isVisible = counter !== 1;
console.log(counter);
return (
<div className="App">
<div>
<button onClick={() => setCounter((counter) => counter 1)}>
Click me
</button>
</div>
{isVisible && (
<div>
Message 1 is: <MyComponent value={counter} />
</div>
)}
<div style={isVisible ? { display: "block" } : { display: "none" }}>
Message 2 is: <MyComponent value={counter} />
</div>
</div>
);
}
我嘗試通過將計數器分配給其鍵來強制子組件重新渲染:
export default function App() {
const [counter, setCounter] = useState(0);
const isVisible = counter !== 1;
console.log(counter);
return (
<div className="App">
<div>
<button onClick={() => setCounter((counter) => counter 1)}>
Click me
</button>
</div>
{isVisible && (
<div>
Message 1 is: <MyComponent key = {counter} value={counter} />
</div>
)}
<div style={isVisible ? { display: "block" } : { display: "none" }}>
Message 2 is: <MyComponent key = {counter} value={counter} />
</div>
</div>
);
}
它有效,但我仍然不知道為什么前一個不起作用,因為props.valueinMyComponent已經改變......提前致謝。
uj5u.com熱心網友回復:
有了這個:
const MyComponent = ({ value }) => {
const [counter] = useState(value);
return <span>{counter}</span>;
};
您告訴 React 將初始狀態設定為value在掛載時傳遞給組件的第一個prop。
當組件重新渲染時,組件已經被掛載,因此傳遞給的值將useState被忽略 - 相反,該counter子項取自of 的狀態MyComponent- 等于初始狀態 in MyComponent,初始valueprop 傳遞。
對于你想要做的事情,你在整個應用程式中只有一個值,你想在任何地方使用,所以你應該只有一個useState呼叫,在父級 - 然后從道具渲染子級中的計數器,這將隨著父狀態而改變。
const MyComponent = ({ value }) => {
return <span>{value}</span>;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/339326.html
標籤:javascript 反应 使用状态
