下面的段代码
import React, { useState, useEffect } from "react"
import ReactDOM from "react-dom"
import "./index.css"
const useUpdate = (fn, dep) => {
console.log('here')
const [count, setCount] = useState(0)
useEffect(() => {
setCount(x => x+1) // 删掉这行就不会两次执行
}, [dep])
useEffect(() => {
if(count > 1) {
fn()
}
}, [count])
}
const App = () => {
const [n, setN] = useState(0)
const add = () => {
setN(n + 1)
}
console.log('app')
useUpdate(() => console.log('n changed'), n)
return (
<div>
{n}
<button onClick={add}>+1</button>
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"))
我尝试着用useEffect
实现componentDidUpdate
,但是运行之后在没点击按钮的情况下,组件App和自定义hook useUpdate执行了两次:
我没有用StrictMode
,但如果我删掉这行setCount(x => x+1)
,就不会两次执行,为什么呢?是不是自定义Hook内部定义的State改变了也会触发使用Hook的组件重新渲染?
介意从无状态组件改成一般组件,不使用hook,