Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在当前状态下调用函数一次_Reactjs_React Hooks - Fatal编程技术网

Reactjs 如何在当前状态下调用函数一次

Reactjs 如何在当前状态下调用函数一次,reactjs,react-hooks,Reactjs,React Hooks,您好,我有一个表,用户可以添加新数据。我想在用户离开页面时呼叫我的服务。所以,我需要使用unmount effect,但它采用我的初始状态([])。如果将状态添加到第二个参数中,则每次状态更改时都会调用该服务。我想用当前状态呼叫服务一次。试试这个 const [posts, setPosts] = useState([]); useEffect(() => () => UpdateAPI.update(posts), []); const handleSubmit =

您好,我有一个表,用户可以添加新数据。我想在用户离开页面时呼叫我的服务。所以,我需要使用unmount effect,但它采用我的初始状态([])。如果将状态添加到第二个参数中,则每次状态更改时都会调用该服务。我想用当前状态呼叫服务一次。

试试这个

  const [posts, setPosts] = useState([]);

  useEffect(() => () => UpdateAPI.update(posts), []);

  const handleSubmit = () => setPosts([...posts, { name: 'johny', surname: 'bravo' }]);
如果你需要进一步的解释,我建议你读一下 试试这个

  const [posts, setPosts] = useState([]);

  useEffect(() => () => UpdateAPI.update(posts), []);

  const handleSubmit = () => setPosts([...posts, { name: 'johny', surname: 'bravo' }]);
如果你需要进一步的解释,我建议你读一下

我认为原因是您的
帖子被卡住了,而且在卸载时它们可能不在那里。您可以尝试使用
useRef


useEffect(() => {
//you mount effect

return () => {
 // your unmount effect, the return is called when the component unmounts
UpdateAPI.update(posts) // here I suppose that your posts are is the current data.
}

},[]);

我想原因是你的
帖子被卡住了,而且在卸载时它们可能不在那里。您可以尝试使用
useRef


useEffect(() => {
//you mount effect

return () => {
 // your unmount effect, the return is called when the component unmounts
UpdateAPI.update(posts) // here I suppose that your posts are is the current data.
}

},[]);
你能在updateapi之前尝试console.log(posts)吗?你能在updateapi之前尝试console.log(posts)吗?