[英]Use useEffect to reinitialize useState
我有一個帶有<div contentEditable />
組件。 該組件使用initialValue
初始化。 onChange
處理程序更新value
。 它看起來像這樣:
const Editable = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return (
<div contentEditable onChange={event => setValue(event.currentTarget.value)}>
{value}
</div>
);
};
現在,如果父組件傳遞一個新的initialValue
、 value
和因此div
的內容不會更新,因為狀態已經初始化。
在這種情況下使用useEffect
是否可以,或者還有其他方法嗎?
const Editable = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
useEffect(() => setValue(initialValue), [initialValue]);
return (
<div contentEditable onChange={event => setValue(event.currentTarget.value)}>
{value}
</div>
);
};
以這種方式使用它完全沒問題。 您可能希望將initialValue
重命名為value
,以表明它不僅僅是默認值。
你可以做的來清理你的代碼是創建一個自定義鈎子來處理這樣的確切情況:
const useUpdatingState = (value) => {
const [internalValue, setInternalValue] = useState(value);
useEffect(() => {
setInternalValue(value)
}, [value]);
return [internalValue, setInternalValue];
};
這將使您的代碼更具可讀性,並使代碼可在您希望此類行為的其他代碼部分中重用。
正如問題中所提出的, useEffect
是正確的解決方案。
const Editable = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
useEffect(() => setValue(initialValue), [initialValue]);
return (
<div contentEditable onChange={event => setValue(event.currentTarget.value)}>
{value}
</div>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.