javascript - useState 和 props 的变化

标签 javascript reactjs react-hooks use-state

我试图了解当您同时拥有 props 时会发生什么和 useState在一个组件中。
我写了一个小例子,它有一个父组件用另一个子组件打印它的数字 -

const MyNumbers = (props) => {
  const [numbers, setNumbers] = useState([...props.arr]);

  function changeNumbers() {
    setNumbers((nums) => [...nums.map(() => Math.floor(Math.random() * 10))]);
  }

  return (
    <div className="MyNumbers">
      <div>
        <button onClick={changeNumbers}>Chane numbers</button>
      </div>
      <div>
        {numbers.map((num, idx) => (
          <SingleNumber key={idx} num={num}></SingleNumber>
        ))}
      </div>
    </div>
  );
};
const SingleNumber = (props) => {
  const [num] = useState(props.num);
  useEffect(() => {
    console.log("useEffect called");
  });
  return <h3>The number is {num}</h3>;
};
Here is the above demoSingleNumber组件使用 useState如您所见,单击“更改数字”操作不会更改子组件中的值。
但是当我写几乎相同的代码但现在 SingleNumber不使用 useState然后单击“更改数字”会更改子组件(like in this demo)中的所有值。
使用 useState 的功能组件是否正确?渲染一次,然后仅在状态更改时才更改,但如果 props 则不会更改改变了?

最佳答案

当 Prop 改变时,OFC 组件“重新渲染”,useEffect Hook SingleNumber显示 您认为每次 Prop 更改时都会运行“渲染阶段”......每次渲染组件时都会运行效果。
enter image description here

const SingleNumber = (props) => {
  const [num] = useState(props.num);
  useEffect(() => {
    console.log("useEffect called"); // <-- logged each time the component renders
  });
  return <h3>The number is {num}</h3>;
};
如果您添加了对 props.num 的依赖项并更新本地状态(实际上不要这样做,这是 react 中的反模式!),每次 Prop 更新时,您都会看到 UI 再次更新。
要回答您的问题:

Is it correct to say that a function component with a useState renders once and then only changed if the state changed but not if the props changed?


不,这在技术上是不正确的,如果“渲染”对您意味着严格 react 渲染组件以计算差异, react 组件在状态或 Prop 更新时重新渲染。是的,如果“渲染”更普遍地意味着您可以直观地看到 UI 更新。

关于javascript - useState 和 props 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65336835/

相关文章:

javascript - 为什么我不应该在reactjs中使用getBoundingClientRect()?

reactjs - 结合基于 NodeJS 的 Passport 身份验证和 ReactJS 前端

typescript - 如何在 Typescript React 中遍历组件的子组件?

javascript - mcv 应用程序在哪里为 View 调整模型数据?

javascript - 如何用 Protractor 检索元素颜色的十六进制值?

javascript - Intl.Collat​​or 对日语进行排序 - 为什么 collat​​or 不首先优先考虑日语字符?

reactjs - React hook useRef 不适用于样式组件和 typescript

javascript - 溢出:自动隐藏内容

reactjs - 第 0 行 : Parsing error: Cannot read property 'map' of undefined"- TypeScript Custom Hook

javascript - 我可以从外部组件使用 useReducer