javascript - 即使我传递相同的引用,React useState 也会重新渲染?

标签 javascript reactjs react-hooks use-effect use-state

我知道的是,如果我们传递相同的状态,useState将不会重新渲染,并且我自己测试了它,但它仅在组件第一次重新渲染时起作用,并将初始状态传递给useState。 但在下面的示例中,即使我传递相同的引用,useState 也会重新渲染组件,并且 useEffect 也知道状态不会改变。 console.logs 的图片显示了该行为。

const arr = [
  { name: 'Khaled', id: 0 },
  { name: 'Mohamed', id: 1 },
  { name: 'Ahmed', id: 2 },
  { name: 'Mohsen', id: 3 },
];

function App() {
  console.log('num $1');

  const [same, setSame] = useState({});

  useEffect(() => {
    console.log('num $3');

    const test = arr.find((el) => el.id === 0);
    console.log(Object.is(same, test));
    setSame(test);
  }, [same]);

  console.log('num $2');

  return <div>welcome</div>;
}

enter image description here

最佳答案

该组件会渲染两次,因为相同状态的初始值为空 { }。在 useEffect 中,您使用新对象更新此状态,然后 useEffect 会触发已添加到相同状态的新值。这是数组中匹配的对象。然后组件重新渲染,这就是为什么你在 console.log 中得到了真实值。

   const arr = [
      { name: 'Khaled', id: 0 },
      { name: 'Mohamed', id: 1 },
      { name: 'Ahmed', id: 2 },
      { name: 'Mohsen', id: 3 },
    ];
    
    function App() {
      console.log('num $1');
    
      const [same, setSame] = useState({}); <= initial value
    
      useEffect(() => {
        console.log('num $3');
    
        const test = arr.find((el) => el.id === 0);
        console.log(Object.is(same, test)); <= changed from false to true because the new value of same
        setSame(test); <= you updated the state
      }, [same]); <= the value of same changed from { } to a new value and that's make the component to re-render
    
      console.log('num $2');
    
      return <div>welcome</div>;
    }

这是您上次评论的更新。

import { useState, useEffect } from "react";

const arr = [
  { name: "Khaled", id: 0 },
  { name: "Mohamed", id: 1 },
  { name: "Ahmed", id: 2 },
  { name: "Mohsen", id: 3 }
];

export default function App() {
  const [same, setSame] = useState(arr);

  useEffect(() => {
    const test = arr.find((el) => el.id === 0);
    console.log(same); <= here the same is [] with 4 objecs
    setSame(test);
    console.log(same); <= here the same is { }
  }, [same]);

  return <div>welcome</div>;
}

就这样。这将导致我们 useEffect 一旦看到相同就会更新。然后它会像我之前提到的那样重新渲染组件。

此处相同具有相同数据。但它们是不同的,因为第一个相同是[],第二个是{}。这就是状态的变化。然后useEffect将重新渲染。

关于javascript - 即使我传递相同的引用,React useState 也会重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72712481/

相关文章:

javascript - 我如何强制 Karma 在每次测试之间重新启动浏览器?

javascript - jQuery onclick 放置器什么都不做

javascript - 使用AutoHotKey输出JavaScript?

javascript - React-md 按钮显示

javascript - 在 React 中使用本地 .json 文件时,import 和 fetch() 有什么区别

javascript - "useSWR is called in function that is niether a React function component nor a custom React Hook function"错误

javascript - ReactJs 不存在授权 header

javascript - 将 PouchDB 与服务器同步

javascript - 无法在 React Native 中使用 useRef() 将 current.focus() 应用于按钮

reactjs - 使用 Jest 和 Enzyme 测试使用 Redux 的功能 React 组件