[英]child component pass props to parent's useState -> returning undefined (react)
[英]useState of props undefined in React
我正在尝试为TextField
提供 props note
的值,但是如果我使用TextInput
,则结果是未定义的,如果我使用note
props,之后我将无法更改TextField
的值。 当我控制台记录这两个值时,它们会呈现两次,如图所示。 我也试过 useEffect 来设置状态。
export default function ProfileNote({ contact }) {
const { note, id } = contact;
const [textInput, setTextInput] = useState(note);
console.log(`textInput: ${textInput}`)
console.log(`note: ${note}`)
const handleTextInputChange = event => {
setTextInput(event.target.value);
};
return (
<FormProvider onSubmit={handleSubmit(onSubmit)}>
<TextField
name="notes"
label="Notes"
onChange={handleTextInputChange}
value={textInput}
/>
</FormProvider>
);
}
console.log 的图像
谢谢你。
我假设调用ProfileNote
的代码从数据库或 API 异步接收contact
。 当异步调用开始时, contact.note
的值仍然是未定义的,但是你的组件仍然被渲染。
这个未定义的值现在用作textField
的初始值。 一旦异步函数调用返回一个值(例如ddfdf
), textField
值将不会更改,因为它已经初始化。
您可以执行以下两项操作之一来解决此问题,具体取决于您希望 UI 的行为方式:
ProfileNote
:<>
{ contact != null && <ProfileNote contact={contact}/> }
</>
contact.note
到textField
,如果在用户编辑时contact
更改,则可能会覆盖用户输入:useEffect(() => setTextInput(note), [note]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.