[英]Can I use useEffect hook and function component when I need to get the pathname props from Link component?
[英]Do I need to use useEffect to rerender a component?
我有一个问题,当它的 props 改变时,让组件更新。 我使用 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 让组件重新渲染解决问题的正确方法还是我找到了一些hacky-solution?
谢谢!
您的解决方案是正确的。
当您向组件添加状态(即使用useState
)时,组件将不再在其 props 更改时自动更新。 相反,您必须使用效果并更新内部状态,就像您在代码中所做的那样。
这是一个相关的问题: React.useState 不会从 props 重新加载状态
您基本上已经“将 props 分叉到状态”——在这一点上,您有责任自己处理状态变化。 另一种选择可能是为用户编辑的文本设置状态,默认情况下undefined
,并执行类似value={userText !== undefined ? userText : props.value}
value={userText !== undefined ? userText : props.value}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.