드롭다운 메뉴를 구현하여 event 객체에 비동기적으로 액세스할 때 오류가 발생했습니다.

6423 단어 Reactreact-hooks
이번에 React에서 드롭다운 메뉴를 구현하고 있어 막힌 부분이 됩니다.

무슨 일이 있었는지





위와 같이 드롭 다운 메뉴를 만들고 테스트하십시오! 그렇다면 오류가 발생했습니다.

1회째는 선택할 수 있습니다만, 2회째의 선택으로 에러가 되어 버린다・・・.

작성한 코드



이번에는 다음과 같은 형태로 구현했습니다.

//ドロップダウンメニューの選択値によって値を変化させるためにuseStateを使う
//今回はドロップダウンメニューが複数あり、一つのuseState内でおさめたかったのでこんな感じで書いた
  const [selects, setSelects] = useState({
    name_id: 0,
    key_id: 0,
  })

//ドロップダウンメニュークリック時のイベントオプションを定義
  const handleDropdownChange = (event: any) => {
    const name = event.target.name
    setSelects(() => {
      return { ...selects, [name]: event.target.value }
    })
  }

//今回は配列からドロップダウンメニューを作成したかったので以下のように書く
//key_idも同じ用に書いてるので今回は省略
  List = names.map((a, index) => (
    <option value={`${a.name_id}`} key={index}>
      {a.name_id}
    </option>
  ))

//表示したい部分で下記のようにして表示
  <select name="name_id" onChange={handleDropdownChange}>
    {List}
  </select>

해결책



공식 에 썼습니다.

볼 수 없는 이유

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynch.

즉, 퍼포먼스의 향상을 위해서 한번 읽힌 이벤트 객체는 재이용되어, 모든 프로퍼티이 null화되어 버리기 때문에, 비동기적으로 이벤트에 액세스 할 수 없다고 하는 것이군요.

내가 위에서 첫 번째는 문제없이 드롭 다운 메뉴에서 선택할 수 있었던 것은 이벤트 콜백이 첫 번째 호출이었기 때문에, 두 번째 이후에는 처음 호출 된 이벤트 객체가 재사용되어 버리기 때문에 , 그 때 다른 값이 선택되어 있으면 에러가 발생한다(=비동기적으로 액세스 할 수 없다)라고 하는 이유였던 것 같습니다.

그래서 해결책. 해결책도 공식적으로 썼습니다.

Note:
If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

즉, 비동기로 액세스 시키기 위해서는 event.persist() 를 사용해 준다는 것입니다.

해결


//ドロップダウンメニュークリック時のイベントオプションを定義
  const handleDropdownChange = (event: any) => {
    event.persist(); //これを追加
    const name = event.target.name
    setSelects(() => {
      return { ...selects, [name]: event.target.value }
    })
  }

위에서 해결!

좋은 웹페이지 즐겨찾기