首页 > 解决方案 > 如何在 React 中正确显示某些变量

问题描述

我正在尝试在 Reactjs 中显示当前年份,但是当我运行代码时,它会引发以下错误:

错误:必须在事件处理程序内部或在 ReconcilerState.enqueueSideEffectIfEnabled 的 useAction、useState 或 useContentProperty 的函数参数内调用调度

这是代码:

//import goes here

const fetchTimer = async () => {
};     
 
const App = () => {
const [timer, setTimer] = useState(null);
const currentYear = new Date().getFullYear();

 setTimer(currentYear);
/*
 useEffect(() => {
    setTimer(currentYear);
  });
*/
    


  return (
    <div>

      <div>Get time and Year:({timer})</div>

    </div>
  );
};

标签: reactjs

解决方案


您正在调用setState函数的根目录。这样,它将在每次渲染时执行。

如果该状态是恒定的,则可以使用该currentYear变量。如果它会被改变,你可以使用useEffect它的第二个数组参数:

  const App = () => {
    const [timer, setTimer] = useState(null);

    useEffect(() => {
      const currentYear = new Date().getFullYear();
      setTimer(currentYear);
    }, []);

    return (
      <div>

        <div>Get time and Year:({timer})</div>

      </div>
  );
};

使用第二个参数,而不是在每次渲染后执行,而是在每次该数组中的值更改时执行。如果没有值,只会在启动时执行:https ://reactjs.org/docs/hooks-effect.html


推荐阅读