redux react状态抛出`TypeError:setEnd不是函数`错误?

ruoxqz4g  于 2023-05-18  发布在  React
关注(0)|答案(1)|浏览(109)

我传递一个状态钩子到我的组件,并使用条件语句更改值。为什么会这样呢?
在我根组件中

const [done, setDone] = useState(0);

<FirstStep current={current} end={done} setEnd={setDone} />;

在组件中,我在useEffect中使用它

useEffect(() => {
    if (
      plateInput != null &&
      mileageInput != null &&
      makeInput != null &&
      bodyInput != null &&
      yearInput != null &&
      kindInput != null &&
      transmissionInput !== null
    ) {
      console.log("object cleared");
      setEnd(current);

      // dispatch(setCompletedStep(current));
    } else {
      console.log("object is not cleared");
      setEnd(current - 1);

      // dispatch(setCompletedStep(current - 1));
    }
  }, [
    plateInput,
    mileageInput,
    makeInput,
    bodyInput,
    yearInput,
    kindInput,
    transmissionInput,
  ]);

误差为TypeError: setEnd is not a function。为什么会这样呢?

jdg4fx2g

jdg4fx2g1#

FirstStep组件中接收props的时候看起来像是出错了,你需要确定一些要点

  • 在根组件中,确保从React导入useState
import {useState}  from 'react';
  • 确保将props正确地传递给嵌套组件
const MyRoot = () => {
  const [done, setDone] = useState(0);

  return <FirstStep current={current} end={done} setEnd={setDone} />;
}
  • 确保在FirstStep组件中正确接收 prop
// you can destructuring to get the props  
const FirstStep = ({end, setEnd, current}) => {
  if(data != null){
    setEnd(current);
  } else {
    setEnd(current - 1);
  }
  return <p>test</p>
}

UPDATE:尝试在useEffect内部设置状态,并使用回调函数检查当前

import {useEffect}  from 'react';

useEffect(() => {
  setEnd(() => {
    if(data !== null) {
      return current
    }else {
      return current - 1
    }
  })
}, [])

相关问题