我只是想知道为什么useCallback不能从组件中获取最新的状态值。组件的状态不存在于外部作用域中。
const [x, updateX] = useState(2);
const handleChange = useCallback(() => {
console.log(x);
// To pick up latest value of x in here, I need to add x in dependency array?
// Why is that this inner arrow function cannot pick x from its outer scope?
}, [])编辑: useRef的最新值是由需要依赖数组中的ref的handleChange ..without获取的。但是,我们需要dependencyArray中的状态值。为什么会这样呢?
我想在引擎盖下创建之间必须有一定的局部范围,这就是x的值是从哪里得到的?不确定我是否正确。
另外,接下来的问题是如何编写类似于useCallback (函数回忆录)之类的东西?用香草js?
发布于 2022-05-25 14:15:02
是的,您需要在依赖项数组中传递X。只有在依赖项更改时,回调才会更改。在本例中,您可以对x的当前状态进行计数和记录。
function Tester(props: TesterProps): JSX.Element {
const [x, setX] = useState(0);
const handleChange = useCallback(() => {
console.log(x);
}, [x]);
return (
<>
<button onClick={() => setX(x + 1)}>Change State</button>
<button onClick={() => handleChange()}>Handle Change</button>
</>
);
}发布于 2022-05-25 14:31:53
要么这样做:
const handleChange = useCallback(() => {
console.log(x);
}, [x]);或者这个:
const handleChange = () => {
console.log(x);
};两者都将打印实际X值。第二个没有回忆录函数,所以它将被重新声明每一个渲染。
https://stackoverflow.com/questions/72379116
复制相似问题