0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React】A component is changing a controlled input to be uncontrolledの解決方法

Posted at

症状

MaterialUIのtextFieldの文字を変更した際に、下記エラーが発生しました。 また、フォーカスをテキストフィールドから外したとき、ラベルが文字と重なってしまう事象も発生しました。
Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, 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

エラー内容をそのままグーグル翻訳に投げると、
「警告:コンポーネントが制御された入力を制御されないように変更しています。これは、値が定義済みから未定義に変更されたことが原因である可能性がありますが、発生しないはずです。コンポーネントの寿命の間、制御された入力要素を使用するか、制御されていない入力要素を使用するかを決定します。詳細:https://reactjs.org/link/managed-components」

該当するTextFieldのソースがこちらになります。

TextField
import React, { useContext,useContext } from 'react';
import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';
import NameDispatch from "../reducer/nameReducer";
import {NameState,NameDispatch} from "../context/Context";

export const MaterialUINameLine() {
    const NameLineState = useContext(NameState)
    const NameLineDispatch = useContext(NameDispatch)

    const handleChange = (event) => {
      NameDispatch({
        type:NAMECHANGE,
        payload:{
          namae: event.target.value
        }
      })
    };

 return (
   <div>
        <form className={classes.root} noValidate autoComplete="off">
          <TextField 
            id="outlined-basic" 
            label="価格" 
            variant="outlined" 
            fullWidth
            value={state.name}
            onChange={handleChange}
        />
       </form>
    </div>
  );
}

解決方法

handleChangeで値を更新する際のReducerに渡す箇所を直したら、エラーが解消されました。
TextField
//before
 const handleChange = (event) => {
      NameDispatch({
        type:NAMECHANGE,
        payload:{
          namae: event.target.value
        }
      })
    };

//after
 const handleChange = (event) => {
      NameDispatch({
        type:NAMECHANGE,
        payload:{
          //↓ここ
          name: event.target.value
        }
      })
    };

エラーの原因としては、値がundefinedやnullになってしまった場合、本エラーが発生するようです。

このエラーが発生のが、値の初期値か値の変更時にnullやundefinedになってしまいがちなので、事象とその周辺を中心にデバッグすると解決しやすそうです。

参考

https://material-ui.com/components/text-fields/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?