在我的 customHook 中,我有一个 onchange 事件处理程序,它values
在下拉菜单中设置所选项目的状态。然后基于 的状态values
,我想在我的 useEffect 中每隔几秒获取一些数据。但是,在每次 useEffect 调用之后,都会调用状态的初始值values
而不是当前状态。
我尝试在代码中使用 useRef 来提取当前值,但它仍然返回初始值。
const [values, setValues] = useState({
name: "",
myid: "my-id"
});
const valuesRef = useRef(values)
const [waitState, setWait] = useState(0)
//state changers
function handleChange(event, id) {
setValues({
...values,
name: event.target.value,
myid: id.props.id,
});
}
useEffect(() => {
valuesRef.current = values
// logs twice, the first log returns the current state, which I want,
// the second logs the initial state, which is useless to me
console.log(values)
let wait = () => {
setTimeout(() => setWait(waitState+1), 10000)
}
async function fetchData() {
wait()
//fetch some data
}
fetchData()
}, [waitState, values])}
我只是希望它返回values
state的当前值