【问题标题】:Getting error while using useState with textarea [closed]将useState与textarea一起使用时出错[关闭]
【发布时间】:2021-08-19 17:29:18
【问题描述】:

我收到此警告。 警告:组件正在将受控输入更改为不受控。这可能是由于值从定义变为未定义引起的,这不应该发生。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。 我正在使用功能组件。我使用 useState 初始化了描述。

 const [description, SetDescription] = useState('');

然后我调用一个 API,从中获取数组数据。 data.description 不为空并给出正确的结果我已经通过 console.log 进行了检查。

 SetDescription(data.description);

这是 textarea 的代码。

<textarea
      id="description"
      value={description}
      onChange={(e) => {
          SetDescription(e.target.value);
      }}
  />             

【问题讨论】:

  • 无法复制。

标签: reactjs textarea use-state react-functional-component


【解决方案1】:

这是因为您正在设置初始状态:

const [description, SetDescription] = useState('');

试试这个:

const [description, SetDescription] = useState();

<textarea
      id="description"
      value={description || ''}
      onChange={(e) => {
          SetDescription(e.target.value);
      }}
  /> 

添加了此工作的沙盒示例https://codesandbox.io/s/blissful-fire-5gf1g?file=/src/App.js

export default function App() {
  const [description, SetDescription] = useState();

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => SetDescription(json.title));
  }, []);

  return (
    <textarea
      id="description"
      value={description || ""}
      onChange={(e) => {
        SetDescription(e.target.value);
      }}
    />
  );
}

此外,您还没有说明如何从 api 获取数据,这很重要,因为它需要在 useEffect 中或使用 useCallback。我已经更新了沙盒链接以显示这一点,因此当您在 textarea 中键入内容时,它将正确更新 textarea 的状态。

【讨论】:

【解决方案2】:

如果我理解正确,那么要从服务器接收数据,您需要使用 useEffect 挂钩。

export default function App() {
  const [description, setDescription] = useState("");

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => setDescription(JSON.stringify(json)));
  }, []);

  return (
    <div className="App">
      <textarea
        value={description || ""}
        onChange={(e) => setDescription(e.target.value)}
      />
      <br />
      <p>{description}</p>
    </div>
  );

从服务器接收到的数据格式是什么?

【讨论】:

  • 我只使用 useEffect 挂钩。 API部分没有问题。
【解决方案3】:

正如您的错误消息所说这可能是由于值从已定义更改为未定义引起的,这不应该发生。 您可以尝试检查响应并仅在 data.description 未定义时才分配值。

if (data && data.description) SetDescription(data.description);

这可能会解决您的警告

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多