reactjs - 如何在 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>
);
};
解决方案
您正在调用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
推荐阅读
- r - 如何下标/上标和斜体 x 轴标签?
- python - 为什么当我尝试使用默认构造函数实例化对象时,由于调用了参数化构造函数而出现错误?
- amazon-web-services - AWS S3 最终一致性:为什么存储桶列表返回一个键,但一个头请求无
- node.js - 如何使用 koa 框架托管 mp3 文件
- haskell - Haskell中作为类型变量的高级类型
- php - 删除附件页面上的页面标题
- matlab - 用于连接字符串的版本兼容方法
- python-3.x - 我想我在 jupyter notebook/python3 中进行故障排除时搞砸了我的文件目录
- python - 使用python对图像中的像素进行基于密度的异常值检测
- spring - Spring Security 和 i18n