[英]Do functions get the latest state value in React?
我的功能組件中有一個函數,它使用狀態中保存的值。 但是,當它被調用時,它的狀態是原始值,而不是更新后的值。 當我在 Chrome React Dev Tools 中查看我的組件時,我看到更新后的值存儲在 state 中。 函數不是應該在 React 中獲取最新的狀態值嗎? 我認為我不必每次都將我的函數包裝在 useEffect 中,它們的狀態取決於它們的變化。 為什么會這樣?
const Editor = (props) => {
const [template, setTemplate] = useState(null);
const [openDialog, setOpenDialog] = useState(false);
useEffect(() => {
if (props.templateId) {
getTemplate(props.templateId));
}
},[]);
const getTemplate = (templateId) => {
{...make API to get template...}
.then((response) => {
if (response.template) setTemplate(response.template);
});
}
/* THIS FUNCTION SAYS TEMPLATE IS ALWAYS NULL */
const sendClick = async () => {
if (template) {
await updateTemplate();
} else {
await initializeTemplate();
}
setOpenDialog(true);
};
}
更新:我想出了這個問題。 sendClick 函數正在我處於狀態的對象內使用。 創建該對象時,它會根據當時的狀態創建一個版本的 sendClick 函數。 我意識到我需要重構我的代碼,以便函數不會以狀態存儲在我的對象中,這樣函數將始終具有最新的狀態值。
請更正那里的代碼,它的setTemplate(template));
不是getTemplate(template));
我猜你在源代碼中有那個權利......如果是,那么,
你陷入了一個陷阱,所有 React 新手都會陷入這個陷阱。
這段代碼背叛了你......
useEffect(() => {
if (props.template) {
setTemplate(template)); // Mentioned as getTemplate(template));
}
},[]); // Here is where you make the mistake
您傳遞給useEffect
的第二個參數稱為Dependencies 。 這意味着如果您的useEffect
依賴於任何狀態或任何變量或函數,則 Ii 應作為[]
的第二個參數傳遞。 現在你應該已經知道答案了。
顯然,您的useEffect
依賴於template
。 您應該將其傳遞到[]
。
所以代碼將是: -
useEffect(() => {
if (props.template) {
setTemplate(template)); // Mentioned as getTemplate(template));
}
},[template]);
現在 React 會在每次template
的值改變時自動運行該函數,因此更新template
。
有關useEffect
更多信息...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.