立即更新状态后尝试获取状态值

时间:2020-07-15 21:29:17

标签: javascript reactjs use-state

我已经用usestate声明了一个变量,如下所示

const [currentStepNumber, setCurrentStepNumber] = useState(0);

然后单击如下所示的移动功能时,我正在更新状态

const handleMove = () => {
   setCurrentStepNumber(currentStepNumber + 1);
   const { label } = Object.values(PROJECT_PHASE).find(s => s.stepNumber === currentStepNumber);
   const projectPhaseID = projectPhaseData.projectPhases.find(a => a.name === label).id;
   console.log(currentStepNumber);
   // need to do API call as well in move function 
};

currentStepNumber仍然只显示0而不是1,并且我不能使用计时器来触发和更新值。还有其他方法可以实现这一目标吗?

我只需要在移动功能中更新currentStepNumber

2 个答案:

答案 0 :(得分:2)

可能可以尝试useEffect

useEffect(() => {
   const postStepData = async () => {
     try {
         // call the api
         const response = await postDataPromise({...data, currentStepNumber});
         setCurrentStepNumber(0);
         setSomeOtherState(false);
     } catch (e) {
         console.log(e)
     }
   }

   const { label } = Object.values(PROJECT_PHASE).find(s => s.stepNumber === currentStepNumber);
   const projectPhaseID = projectPhaseData.projectPhases.find(a => a.name === label).id;
   console.log(currentStepNumber);
   /*
    * as an example only call api on step 4
   */
   if (currentStepNumber === 4) {
      void postStepData();
   }
}, [currentStepNumber])

const handleMove = () => setCurrentStepNumber(currentStepNumber + 1);

参考:

答案 1 :(得分:0)

您应在React's useEffect中使用新的currentStepNumber

const MyComponent = () => {
  const [currentStepNumber, setCurrentStepNumber] = useState(0);
  
  const handleMove = () => {
    setCurrentStepNumber(currentStepNumber + 1);
  };

  useEffect(() => {
    const { label } = Object.values(PROJECT_PHASE).find(s => s.stepNumber === currentStepNumber);
    const projectPhaseID = projectPhaseData.projectPhases.find(a => a.name === label).id;
    console.log(currentStepNumber);
  }, [currentStepNumber])

  return (
    <>{/* some jsx */}</>
  )
}