axios useEffect设置文本字段的值无效

idfiyjo8  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(137)

我正在尝试使用useEffect来设置加载时MUI TextField的初始值。该值是从数据库中提取的。大多数情况下这是有效的,但是在某些情况下useEffect不能正确更新textfield的值,它只是空白。

我的问题:如何更改代码以确保从useEffect提取的数据在加载时始终设置文本字段的初始值?

const [introText, setIntroText] = useState();

useEffect(() => {
  const fetchResults = async () => {
    const result = await axios({
      method: "GET",
      url: "https://server.site.com/userData",
      withCredentials: true,
    });
    setIntroText(result.data.introEssayText);
  };

  fetchResults();
}, []);

<TextField
  onChange={(e) => setIntroText(e.target.value)}
  value={introText}
  onInput={handleUpdatedIntro}
/>;
gr8qqesn

gr8qqesn1#

  • “这在大多数情况下有效,但在某些情况下,useEffect无法正确更新textfield的值,它只是空白”*。确保result.data.introEssayText在所有用例中不是空的。

除此之外,有const [introText, setIntroText] = useState()将触发下面的警告,为一个正常的input,我相信TextField将回落。

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components

而不是使用const [introText, setIntroText] = useState(""),因此输入的初始值是"",而不是undifined

相关问题