[英]Why am I getting error “hook cannot be called inside a callback” when setting state in React?
I am new to React, and I am trying to integrate React hooks in some of the projects that the React course I follow uses.我是 React 的新手,我正在尝试将 React 钩子集成到我遵循的 React 课程使用的一些项目中。 This example is supposed to add an input field which sets the background color of a page.
此示例应该添加一个设置页面背景颜色的输入字段。 When I load the page, after 1 second, I get the following error
当我加载页面时,1 秒后,出现以下错误
src\App.js
Line 16:43: React Hook "useBackgroundColor" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
What might be the issue here?这里可能有什么问题? I haven't managed to figure it out.
我还没有弄清楚。
Thank you!谢谢!
import logo from "./logo.svg";
import "./App.css";
import UserItem from "./UserItem";
import React, { useState } from "react";
function App() {
const [backgroundColor, useBackgroundColor] = useState("purple");
return (
<div className="App" style={{ background: backgroundColor }}>
<h1>Lista utilziatori:</h1>
<input type="color" onChange={event => useBackgroundColor(event.target.value)} />
</div>
);
}
export default App;
Functions prefixed with use
are interpreted by React to be hooks.以
use
为前缀的函数被 React 解释为钩子。 But here, your useBackgroundColor
isn't actually a hook, it's just a state setter function.但是在这里,您的
useBackgroundColor
实际上并不是一个钩子,它只是一个状态设置器函数。 Rename it to something more appropriate - the usual convention is to prefix the state variable with set
.将其重命名为更合适的名称 - 通常的约定是在状态变量前加上
set
。 Change改变
const [backgroundColor, useBackgroundColor] = useState("purple");
to到
const [backgroundColor, setBackgroundColor] = useState("purple");
and then reference setBackgroundColor
in your code.然后在您的代码中引用
setBackgroundColor
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.