【发布时间】:2020-07-15 21:29:17
【问题描述】:
我已经用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。
【问题讨论】:
-
不,更新状态后我也不必进行其他操作
-
没关系;设置状态是异步的;那是 React 101(还有:愚蠢的“这能回答你的问题吗?”当你标记为欺骗时,SO 会自动插入)
-
@ChrisG 因为这个问题几乎每天都会被问到,所以我已经把它搞定了。 ;) 虽然,根本原因是完全一样的......反应组件生命周期和协调。
标签: javascript reactjs use-state