简体   繁体   English

我需要使用 useEffect 来重新渲染组件吗?

[英]Do I need to use useEffect to rerender a component?

I had an issue getting a component to update when it´s props changed.我有一个问题,当它的 props 改变时,让组件更新。 I got it to work using useEffect, but am unsure if it is the correct way to solve my problem.我使用 useEffect 让它工作,但我不确定这是否是解决我的问题的正确方法。

This is my code:这是我的代码:

import * as React from "react";
import "./styles.css";

const InputWithDefaultValue = (props: any) => {
  const { value } = props;

  //had to add this to get my component to rerender when the button in App-Component was pressed
  React.useEffect(() => {
    setText(value);
  }, [value]);

  const [text, setText] = React.useState(value);

  return (
    <input
      value={text}
      onChange={(e) => setText(e.currentTarget.value)}
    ></input>
  );
};

export const App = () => {
  const [value, setValue] = React.useState("Foo");
  return (
    <div className="App">
      <InputWithDefaultValue value={value} />
      <button onClick={() => setValue(Math.random().toString())}>Update</button>
    </div>
  );
};
export default App;

I was thinking when I updated the props of InputWithDefaultValue it would get rerendered.我在想,当我更新InputWithDefaultValue的道具时,它会被重新渲染。 Is using useEffect to get the component to rerender the correct way to solve the problem or did I find some hacky-solution?是使用 useEffect 让组件重新渲染解决问题的正确方法还是我找到了一些hacky-solution?

Thanks!谢谢!

Your solution is correct.您的解决方案是正确的。

When you add state to a component (ie with useState ) then the component will no longer automatically update when its props change.当您向组件添加状态(即使用useState )时,组件将不再在其 props 更改时自动更新。 Rather, you'd have to use an effect and update an internal state, exactly as you have in your code.相反,您必须使用效果并更新内部状态,就像您在代码中所做的那样。

Here's a related question: React.useState does not reload state from props这是一个相关的问题: React.useState 不会从 props 重新加载状态

You've basically "forked props into state" - at that point you're responsible for taking care of the state changes yourself.您基本上已经“将 props 分叉到状态”——在这一点上,您有责任自己处理状态变化。 Another option might be to to have state for user-edited text, undefined by default, and do something like value={userText !== undefined ? userText : props.value}另一种选择可能是为用户编辑的文本设置状态,默认情况下undefined ,并执行类似value={userText !== undefined ? userText : props.value} value={userText !== undefined ? userText : props.value}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM