Nextjs:为useEffect设置优先级
Nextjs: set priority for useEffect
这是我的_app.tsx
useEffect(() => {
console.log(1)
}, []);
这是我的 index.tsx
useEffect(() => {
console.log(2)
}, []);
所以,在我的控制台打印 21
但是我想打印12
如何为 运行 _app
设置 useEffect
的优先级?
简答
您不能跨组件设置优先级。
长答案
不管为什么有人首先需要跨组件控制 useEffect
的优先级,无法控制 useEffect
被不同组件 运行 的顺序在我们这边。正在关注 this article、
useEffect
runs the clean up and the new effect before moving to the
next component (depth) first and doing the same.
这意味着子组件将首先在 useEffect
运行 那里,然后是其父组件,这解释了为什么 index.tsx
中的 useEffect
在 [=17] 之前执行=].这是因为 app.tsx
可以被视为包含整个应用程序的容器,使其成为任何其他组件的父级。
但是,control
useEffect 顺序的可能解决方法是仅通过使用标志在第一次渲染时跳过 useEffect
,进一步解释 here。
const notInitialRender = useRef(false)
useEffect(() => {
if (notInitialRender.current) {
document.title = `Current count is ${count}`
} else {
notInitialRender.current = true
}
}, [count])
这是我的_app.tsx
useEffect(() => {
console.log(1)
}, []);
这是我的 index.tsx
useEffect(() => {
console.log(2)
}, []);
所以,在我的控制台打印 21
但是我想打印12
如何为 运行 _app
设置 useEffect
的优先级?
简答
您不能跨组件设置优先级。
长答案
不管为什么有人首先需要跨组件控制 useEffect
的优先级,无法控制 useEffect
被不同组件 运行 的顺序在我们这边。正在关注 this article、
useEffect
runs the clean up and the new effect before moving to the next component (depth) first and doing the same.
这意味着子组件将首先在 useEffect
运行 那里,然后是其父组件,这解释了为什么 index.tsx
中的 useEffect
在 [=17] 之前执行=].这是因为 app.tsx
可以被视为包含整个应用程序的容器,使其成为任何其他组件的父级。
但是,control
useEffect 顺序的可能解决方法是仅通过使用标志在第一次渲染时跳过 useEffect
,进一步解释 here。
const notInitialRender = useRef(false)
useEffect(() => {
if (notInitialRender.current) {
document.title = `Current count is ${count}`
} else {
notInitialRender.current = true
}
}, [count])