React componentWillunMount挂钩(使用效果)与React Hook(Usestate)阵列空无一人吗?
在componentwillunmount上,我想在usestate内部将数组发送到posttrequest函数。
我的USESTATE数组:
const [array, setArray] = useState([]);
我的componentWillunMount函数:
useEffect(() => {
return () => {
console.log(array); // logs "[]"
// TODO: Send to a post request to BE
}
}, [])
我也具有“正常”使用效果,可在我的Usestate数组上倾听。当我在其中添加三个元素时,控制台日志显示里面有三个elemetns
useEffect(() => {
console.log('array: ', array); // logs "(3) [{…}, {…}, {…}]"
}, [array]);
在我的componentwillunmount函数中为空数为空?
编辑:将数组添加到使用效果的依赖的依赖性中,每次更新数组时都会执行该函数,这不是所需的内容。该函数只能在卸载时执行数组的值
Upon componentWillUnmount I want to send an array inside a useState to a postRequest function.
My useState array:
const [array, setArray] = useState([]);
My componentWillUnmount function:
useEffect(() => {
return () => {
console.log(array); // logs "[]"
// TODO: Send to a post request to BE
}
}, [])
I do also have a "normal" useEffect that listens on my useState array. When I add three elements inside it, the console logs shows there are three elemetns inside it
useEffect(() => {
console.log('array: ', array); // logs "(3) [{…}, {…}, {…}]"
}, [array]);
How come the array is empty in my componentWillUnmount function?
Edit: Adding array to the dependecy of the useEffect will make the function execute every time that array is updated, which is not what is desired. The function should only execute upon unmount with the values of the array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为该变量的值没有在挂钩内部更改,因为它在
componentDidmount
上启动,并且由于第二个参数为空,因此未收到更新。由于您只想在组件卸载而不是每次值都会变化时触发一次:
您可以使用
useref
“保留”值,而无需重新启动组件。It's because the value of the variable did not changed inside hook because it initiated on
componentDidMount
and did not received an update because the second parameter is empty.Since you only want to trigger it once if the component unmounts and not every time the value changes:
you can use
useRef
to "preserve" the value without rerendering the component.当将空依赖关系数组作为第二个参数传递给
使用效果
时,useffect
回调中的代码只能在MOUNT上运行。此刻,数组仍然空。当您还将数组添加到这样的第一个使用效果的依赖项数组中时,它是否有效?
顺便说一句,我认为您也可以将两者结合在一起:
When passing an empty dependency array as second argument to
useEffect
, the code inside theuseEffect
callback will only be run on mount. At this moment, array is still empty.Does it work when you also add the array to the dependency array of the first useEffect like this?
BTW, I think you can also combine the two like this: