繁体   English   中英

React 中未定义的 props 的 useState

[英]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.notetextField ,如果在用户编辑时contact更改,则可能会覆盖用户输入:
useEffect(() => setTextInput(note), [note]);

暂无
暂无

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

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