Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

React Hook 修改状态的时候,传的状态值没有变化,但第一次依旧重新渲染了?

`

function Counter4() {
     const [counter, setCounter] = useState(1);
     console.log('render', counter);
     return (
            <>
                <p>{counter}</p>
                <button onClick={() => setCounter(2)}>setCounter</button>
                <button onClick={() => setCounter(counter)}>set same counter</button>
            </>
    )
}

`

image.png
首次加载时候 控制台第一次 输出 render 1
首先点击第一个按钮, counter变成了2,控制台输出 render 2

这时候点击第二个按钮,setCounter传入的值是counter,按理说我传的状态值没有变化,不会重新渲染,控制台不应该输出的,但是 依然输出了 render 2,当我继续点击的时候 就不会render了
image.png

请问这是什么原因呢,是和Object.is浅比较有关吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

React Hooks文件里有说到Bailing out of a state update:

Note that React may still need to render that specific component again before bailing out.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...