更新JSX变量,并在每次重现&Quot;问题后丢失useEffect&Quot; [英] Updating a JSX Variable with useEffect "lost after each rerender" Issue

查看:26
本文介绍了更新JSX变量,并在每次重现&Quot;问题后丢失useEffect&Quot;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试根据情况添加可选的JSX,所以我已将它们初始化为NULL,并在合适的时间更新它们,使其包含JSX。

//initialize potentially unused parts
let monitor = null;
let keyboard = null;

...

稍后在我的JSX中,我使用它们来仅显示存在的信息。

{monitor}
{keyboard}

我做了一些研究,发现我的状态没有更新,因为useState是异步的,所以我设置了useEffect挂钩,试图在最终更新状态时更新这些变量。

const [monitorState, setMonitorState] = useState(0);
const [keyboardState, setKeyboardState] = useState(0);

useEffect(() => {
    monitor = (
        <li>
            <span className="bold">Monitor: </span>
            {monitorState.title}}
            <span className="right">${monitorState.price}</span>
        </li>
    );
}, [monitorState]);

const handler = (item) => {
    if (item.type === "monitor") {
        setMonitorState(item);
    }
    ...
}

在模式组件中单击"添加"按钮时调用此处理程序:

<a
   onClick={() => props.handler(item)}
   href="#!"
   className="modal-close btn waves-light waves-effect grey darken-3 
   white-text modal-item-add">
   Add
</a>

但是,我收到一个错误:

从内部Reaction Hook useEffect对‘monitor’变量的赋值将在每次呈现后丢失。若要在一段时间内保留该值,请将其存储在useRef Hook中,并将变量值保留在".current"属性中。否则,您可以直接在useEffect内移动此变量。

我对useRef究竟如何解决这个问题以及如何实现这个问题感到困惑。我查看了其他线程,但它们都没有更新JSX变量。

推荐答案

每次重新呈现功能组件时,底层反应代码都会再次调用该函数。在此重现器中将发生的情况是,函数内的所有变量都将被重新初始化,但状态和引用除外,因为它们由Reaction分别存储。

按照建议,让我们看看如何使用Refs纠正这个问题:

const monitorRef = useRef(null);

useEffect(() => {
    monitorRef.current = (
        <li>
            <span className="bold">Monitor: </span>
            {monitorState.title}}
            <span className="right">${monitorState.price}</span>
        </li>
    );
}, [monitorState]);

return (
  <div>{monitorRef.current}</div>
)
此处,ref值与RECTIVE一起存储,因此不会在重现器上销毁。

但是,从您共享的代码看,您似乎只需将monitor代码添加到render

const [monitorState, setMonitorState] = useState(null);

const handler = (item) => {
    if (item.type === "monitor") {
        setMonitorState(item);
    }
    ...
}

return monitorState ? (
  <li>
     <span className="bold">Monitor: </span>
     {monitorState.title}}
     <span className="right">${monitorState.price}</span>
  </li>
) : null;

这篇关于更新JSX变量,并在每次重现&Quot;问题后丢失useEffect&Quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆