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