javascript - 反应钩子是否通过 CDN 链接在一个简单的单个 html 文件中工作?
问题描述
下面的html&js有什么问题,我不能用钩子!...这是我项目中唯一的文件(没有其他文件或包管理器)
<html>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin ></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin ></script>
<script>
function Component() {
React.useEffect(() => console.log('Hooks are working!!'))
return React.createElement('h1', null, 'Hello World')
}
ReactDOM.render(Component(), document.getElementById('root'))
</script>
</body>
</html>
我在浏览器控制台中收到以下错误(您可以通过将 html 复制到index.html
文件中并双击它来重现它):
react.development.js:1501 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
at resolveDispatcher (react.development.js:1501)
at Object.useEffect (react.development.js:1544)
at Component (index.html:8)
at index.html:11
resolveDispatcher @ react.development.js:1501
useEffect @ react.development.js:1544
Component @ index.html:8
(anonymous) @ index.html:11
如果我注释掉React.useEffect(() => console.log('Hooks are working!!'))
它可以工作......但没有反应钩子:(
解决方案
React.createElement
不仅需要用于 . h1
,还需要用于整个容器 - Component
. 这样Component()
做不会让 React 将其与普通函数调用区分开来(因此不允许内部的钩子调用) -Component
改为传递createElement
:
<div id="root"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin ></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin ></script>
<script>
function Component() {
React.useEffect(() => console.log('Hooks are working!!'))
return React.createElement('h1', null, 'Hello World')
}
ReactDOM.render(React.createElement(Component), document.getElementById('root'))
</script>
推荐阅读
- ubuntu-16.04 - Buildozer 无法执行 Kivy 中的最后一个命令
- ios - 尝试使用 Swift 将类型 [Any] 转换为 JSON 时出错
- html - 如何用另一个 HTML 元素更改拖动 HTML 元素?
- scala - 用 scala-cats 展平嵌套的 Ior's
- r - 尝试执行 RFE 时出现无效的 mtry 错误?
- sql-server - SQL-Server 获取介于两个日期之间的每一天的数据
- java - Java餐厅计费系统
- liquid - Azure API 管理集主体“液体”模板因“流不可读”而失败
- html - 当空间不足时,如何使我的 flexbox 中的每个跨度都具有相同的宽度,而一半的项目换行?
- react-native - 反应原生:动画未在发布模式下触发