我是否需要使用useEffect重新渲染组件?

时间:2020-09-09 16:04:46

标签: javascript reactjs use-effect use-state

我在更换道具时无法更新组件时遇到问题。我可以使用useEffect来工作,但是不确定这是否是解决我的问题的正确方法。

这是我的代码:

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;

我在想,当我更新 InputWithDefaultValue 的道具时,它将重新呈现。是使用useEffect来使组件重新渲染以解决问题的正确方法,还是找到了一些解决方案?

谢谢!

2 个答案:

答案 0 :(得分:0)

您的解决方案是正确的。

当您向组件添加状态(即使用useState)时,组件的属性更改时,该组件将不再自动更新。相反,您必须完全按照代码中的方式使用效果并更新内部状态。

这是一个相关的问题:React.useState does not reload state from props

答案 1 :(得分:0)

您基本上已经“将道具派上了用场”-在这一点上,您负责照顾自己的状态变化。另一种选择可能是让用户编辑的文本具有状态,默认为undefined,并执行类似value={userText !== undefined ? userText : props.value}

的操作