记录学习React遇到的问题
感觉更新了React18之后现在学React着实有点坑。18版本是今年才发布的,所以除了文档之外可以查到的资料实在是少之又少,很多基于新版本写法问题的报错也很难搜索到,我的内心也是极度崩溃。。。看了官网尽力找到一些不知道对不对的解决办法,记录一下吧
1.React18 解决 unmountComponentAtNode()被弃用warning问题
Warning: You are calling ReactDOM.unmountComponentAtNode() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?
Warning: unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. Instead, have the parent component update its state and rerender in order to remove this component.
import React from 'react'
import { createRoot } from 'react-dom/client'
export default function Demo() {
const [count, setCount] = React.useState(0)
const [name, setName] = React.useState('tom')
function add() {
setCount(count + 1)
}
function changeName() {
setName('jack')
}
React.useEffect(() => {
const timer = setInterval(() => {
setCount(count => count + 1)
// setCount(count + 1)为什么无法正确出现效果
}, 1000)
return () => {
clearInterval(timer)
}
}, [])
function unMount() {
// ReactDOM.unmountComponentAtNode(document.getElementById('root'))
const root = createRoot(document.getElementById('root'));
root.unmount()
}
return (
<div>
<h1>当前求和为{count}</h1>
<h1>当前名字为{name}</h1>
<button onClick={add}>点我加一</button>
<button onClick={changeName}>点我改名</button>
<button onClick={unMount}>卸载组件</button>
</div>
)
}
以上代码在点击了button卸载按钮之后仍然弹出Warning
Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.
这个Warning暂时没有找到有效的解决办法,但是卸载功能已经实现,暂时只能被迫忽略了。以后找到解决办法再更新吧
2.解决引入 createStore被划掉问题
解决这个问题有两种方法:
-
如果想继续保留createStore的话只需要根据Vscode的提示将import改成如下就能正常使用了
import { legacy_createStore as createStore } from "redux"; -
Vscode推荐使用configure store代替createstore所以才会出现这个情况具体的教程如下
https://redux-toolkit.js.org/api/configureStore
3.redux中使用store.subscribe在App.js文件中监测状态发生变化的写法
由于React18中渲染DOM节点的写法发生改变,如果项目中应用到了redux,必须手动监测状态的变化,写法如下:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
store.subscribe(() => {
root.render(<App />)
})
4.快速删除废弃文件 如node_modules
npm install rimraf -g
rimraf node_modules
分类:
04.React杂记
标签:
React
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步