开发者问题收集

React-未捕获的类型错误:无法读取未定义的属性(读取“has”)

2022-11-15
658

下面的组件用于测试如何使用 useState 更新集合。错误发生在 state.has(num) useState 中的 state 变量是一个集合,并且 has 是一个集合内置函数。为什么会发生此错误?

import { useState } from "react";

function App() {
  const [state, setState] = useState(new Set());

  console.log(typeof state);

  function clickHandler(num) { 
    if (!state.has(num)) {
      setState(prevState => {
        return setState(new Set(prevState).add(num))
      })
    } else { 
      setState((prevState) => {
        return setState(new Set(prevState).delete(num));
      });
    }
  }
  return (
    <>
      <button onClick={() => clickHandler(1)}>1</button>
      <button onClick={() => clickHandler(2)}>2</button>
      <button onClick={() => clickHandler(3)}>3</button>

      { state}
    </>
  );
}

export default App;
2个回答

setState 返回 undefined

setState 的回调中删除 setState

function clickHandler(num) { 
    if (!state.has(num)) {
      setState(prevState => {
        const set = new Set(prevState)
        set.add(num)
        return set
      })
    } else { 
      setState((prevState) => {
        const set = new Set(prevState)
        set.delete(num);
        return set
      });
    }
  }
Konrad
2022-11-15
import { useState, useRef, useEffect } from "react";

function App() {
  const [stateValue, setStateValue] = useState(0);
  const previousValue = useRef(null);
  console.log(typeof stateValue);

  useEffect(() => {
    previousValue.current = stateValue;
  }, [stateValue]);

  function clickHandler(num) {
    setStateValue(num);
  }

  return (
    <>
      <button onClick={() => clickHandler(1)}>1</button>
      <button onClick={() => clickHandler(2)}>2</button>
      <button onClick={() => clickHandler(3)}>3</button>
      <br />
      <h5>number: {stateValue}</h5>
      <h5>previous number: {previousValue.current}</h5>
    </>
  );
}

export default App;

祝你好运 :)

Saqib Ali
2022-11-15