我正在尝试新的 React Hooks,但我有点卡住了,因为更新本地状态时 UI 没有更新。这是我的代码,
import React, { useState, useEffect } from 'react';
import Post from './Post'
import PostForm from './PostForm';
import axios from 'axios';
function PostsList() {
const [posts, setPosts] = useState([]);
// setting up the local state using useEffect as an alternative to CDM
useEffect(() => {
axios.get('...')
.then(res => {
// the resposne is an array of objects
setPosts(res.data)
})
})
const handleSubmit = (data) => {
// the data I am getting here is an object with an identical format to the objects in the posts array
axios.post('...', data)
.then(res => {
// logging the data to validate its format. works fine so far..
console.log(res.data);
// the issue is down here
setPosts([
...posts,
res.data
])
})
.catch(err => console.log(err))
}
return (
<div>
<PostForm handleSubmit={handleSubmit} />
<h3>current posts</h3>
{ posts.map(post => (
<Post key={post.id} post={post} />
)) }
</div>
)
}
当我提交表单时,UI 会闪烁一瞬间,然后在没有新更新的情况下渲染当前状态,似乎有什么东西阻止它重新渲染新状态。
如果需要更多代码/说明,请在下面发表评论。
提前致谢。
好的,通过@skyboyer 的有用提示解决了问题,
所以最初发生的是useEffect()
行为就像componentDidMount()
& componentDidUpdate()
同时,这意味着每当状态有更新时,useEffect()
被调用,这意味着使用来自服务器的初始数据重置状态。
为了解决我需要做的问题useEffect()
在创建/渲染组件时仅渲染组件一次,而不是每次状态更新时渲染组件。这是通过添加一个空数组作为第二个参数来完成的useEffect()
功能。如下所示。
useEffect(() => {
axios.get('...')
.then(res => {
setPosts(res.data)
})
}, [])
thanks :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)