[英]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.