React Hooks不会更新以使用向下传递然后存储的道具。通常,我可以通过调用useEffect内部的功能来解决useState问题,但是在这种情况下,我需要在click事件之后进行更新:
const [currentLayer, setCurrentLayer] = useState();
useEffect(() => {
console.log(props.currentLayer) // props.currentLayer is defined
setCurrentLayer(props.currentLayer);
}, [props.currentLayer]);
useEffect(() => {
console.log(currentLayer); // currentLayer state is defined
}, [currentLayer]);
/*
* Called when the timeline product is clicked
*/
const clickHandler = e => {
console.log(currentLayer); // currentLayer state is undefined
currentLayer.getSource().updateParams({ TIME: e.time });
};
return <Timeline options={props.timelineOptions} items={items} clickHandler={e => clickHandler(e)} />;
在调用clickHandler时,尽管已进行了较早的设置,但currentLayer状态仍未定义。
结合使用useEffect和clickHandler的最佳方法是什么,或者我是否还缺少其他东西?
答案 0 :(得分:0)
import React from 'react'
const Component = (props) => {
// ... your other logic
const [currentLayer, setCurrentLayer] = useState(props.currentLayer)
const clickHandler = e => {
currentLayer.getSource().updateParams({ TIME: e.time });
}
return <Timeline options={props.timelineOptions} items={items} clickHandler={clickHandler} />
}
我看不到您需要useEffect挂钩的原因。实际上,您不应在此组件中设置currentLayer道具,而应按原样使用它。这样,当props.currentLayer发生更改时,此组件也会重新渲染。
答案 1 :(得分:0)
const clickHandler = e => {
props.currentLayer.getSource().updateParams({ TIME: e.time });
};