Closed5

React: UncontrolledとかControlledとか

CaaaaatsCaaaaats

React触ってたら時たま以下のようなエラーに遭遇する

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.
CaaaaatsCaaaaats

Stateの値がUndefinedかnullのタイミングがあると起きるらしい。

サンプルコード

import { useLayoutEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [todos, setTodos] = useState([]);
  const [currentTodo, setCurrentTodo] = useState(); //このStateの初期値がundefined or null になっている

 console.log(currentTodo); // 出力はundefined

  const handleAddTodo = () => {
    setTodos((todo) => [...todo, { id: todo.length + 1, title: currentTodo }]);
    setCurrentTodo("");
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>{`${todo.id} : ${todo.title}`}</li>
        ))}
      </ul>
      <input
        value={currentTodo}
        onChange={(e) => {
          e.preventDefault();
          setCurrentTodo(e.target.value);
        }}
      />
      <button
        onClick={handleAddTodo}
        disabled={currentTodo === "" ? true : false}
      >
        Submit
      </button>
    </div>
  );
}


CaaaaatsCaaaaats
・・・
export default function App() {
  const [todos, setTodos] = useState([]);
  const [currentTodo, setCurrentTodo] = useState(''); //初期値を指定

 console.log(currentTodo); // 出力は'' (string)
・・・
このスクラップは2021/12/06にクローズされました