【问题标题】:Why setting state to a constant triggers rerender two times?为什么将状态设置为常量会触发两次重新渲染?
【发布时间】:2019-07-22 14:53:40
【问题描述】:

演示:

https://codesandbox.io/s/2zkxyk31oy

import React, { useState } from "react";
import ReactDOM from "react-dom";

function App() {
  console.log("render");
  let [val, setVal] = useState(0);
  return <button onClick={() => setVal(1)}>go</button>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我期望看到的是两个渲染调用:初始调用和由状态变化引起的调用。

第三个setState 调用应该没有效果,因为如果状态没有改变,react 会退出渲染。 https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update

到底发生了什么?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您提供的文档链接指出:

    请注意,React 在退出之前可能仍需要再次渲染该特定组件。这不应该是一个问题,因为 React 不会不必要地“深入”

    看来行为与文档所说的一致。为了测试这一点,您可以检查是否正在渲染子组件。像这样的:

    import React, { useState } from "react";
    import ReactDOM from "react-dom";
    
    function App() {
      console.log("render");
      let [val, setVal] = useState(0);
      return <button onClick={() => setVal(1)}><Child/></button>;
    }
    
    function Child() {
      console.log('render the child')
      return <span>go</span>
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    现在控制台中的结果是:

    render 
    render the child 
    render 
    render the child 
    render 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2022-01-25
      • 2019-07-31
      • 1970-01-01
      • 2020-11-04
      • 2020-07-26
      相关资源
      最近更新 更多