为什么 React hook useState 不增加索引 onClick?



我不明白为什么在SwitchProject函数内的setProjectIndex不更新我的projectIndex状态:

const WorkPreview = ({project, projects}) => {
const [currProject, setCurrProject] = useState(projects[0]);
const [projectIndex, setProjectIndex] = useState(0);
useEffect(() => {
console.log("useEffect idx", projectIndex) // log: 1 when onClick to Right Button
}, [projectIndex])
const SwitchProject = (incrDecrAmount) => {
let nextIndex = projectIndex + incrDecrAmount;
if (nextIndex >= 0 && nextIndex < (projects.length-1)) {
setProjectIndex(projectIndex + incrDecrAmount); // sets 0
console.log("projectIndex", projectIndex)  // log: 0 when onClick to Right Button (increment by 1)
console.log("nextIdx", nextIndex) // log: 1 when onClick to Right Button
setCurrProject(projects[projectIndex]);
console.log("", projects[projectIndex]); // gives projects[0] not projects[1]
}
}

return (
<div className="works__preview" id="workPreview">
<button className="works__itemBtn" id="btnfixedLeft" onClick={() => { SwitchProject(-1) }}>
<Icon.ArrowLeft></Icon.ArrowLeft>
</button>
<button className="works__itemBtn" id="btnfixedRight" onClick={() => { SwitchProject(1) }}>
<Icon.ArrowRight></Icon.ArrowRight>
</button>
</div>
)

我检查了其他问题,并尝试不同的方法,但给出相同的结果

谁能给我解释一下并给我解决方案吗?

既然你只是在增加/减少值,在你的位置,我只会使用userReducer钩子

import React, { useState, useEffect, useReducer } from "react";
const useCounterHook = (state: { count: number }, action: { type: string }) => {
switch (action.type) {
case "increment":
return { count: ++state.count };
case "decrement":
return { count: --state.count };
default:
throw new Error();
}
};
const WorkPreview  = ({ project, projects }) => {
const [currProject, setCurrProject] = useState(projects[0]);
const [state, dispatch] = useReducer(useCounterHook, { count: 0 });
useEffect(() => {
console.log("state effect", state.count);
console.log("state next effect", state.count + 1);
setCurrProject(projects[state.count < 0 ? 0 : state.count]);
}, [projects, state]);
useEffect(() => {
console.log("currProject", currProject);
}, [currProject]);
return (
<div className="works__preview" id="workPreview">
<button
className="works__itemBtn"
id="btnfixedLeft"
onClick={() => dispatch({ type: "decrement" })}
>
<Icon.ArrowLeft></Icon.ArrowLeft>
</button>
<button
className="works__itemBtn"
id="btnfixedRight"
onClick={() => dispatch({ type: "increment" })}
>
<Icon.ArrowRight></Icon.ArrowRight>
</button>
</div>
);
};

最新更新