Javascript 反应钩';s状态未得到更新
我构建了一个React钩子,如下所示:Javascript 反应钩';s状态未得到更新,javascript,reactjs,Javascript,Reactjs,我构建了一个React钩子,如下所示: const Index = (props) => { const [posts, setPosts] = useState([]) useEffect(() => { const getPosts = async () => { const posts = await getPostFromWebService() for (let i of posts) { setPosts([
const Index = (props) => {
const [posts, setPosts] = useState([])
useEffect(() => {
const getPosts = async () => {
const posts = await getPostFromWebService()
for (let i of posts) {
setPosts([ ...posts, i ])
}
}
getPosts()
}, [])
// ... remaining code
}
但是,即使web服务返回5篇文章,只有最后一篇文章在posts
状态下得到更新。因此,它只收到一个帖子,而不是5个
我做错了什么?听起来你想要这样的东西。在这里,我们将让useffect监听postCount中的任何更改,以便触发您的逻辑来获取更多的帖子
const Index = (props) => {
const [posts, setPosts] = useState([])
const [postCount, setPostCount] = useState(0)
useEffect(() => {
const getPosts = async () => {
const newPosts= await getPostFromWebService()
setPosts([...posts, newPosts])
}
}, [postCount])
return(
<div>
<button onClick={() => setPostCount(postCount + 5)}>Get more posts</button>
</div>
)
}
const Index=(道具)=>{
const[posts,setPosts]=useState([])
常量[postCount,setPostCount]=useState(0)
useffect(()=>{
const getPosts=async()=>{
const newPosts=wait getPostFromWebService()
setPosts([…posts,newPosts])
}
},[后计数])
返回(
setPostCount(postCount+5)}>获取更多帖子
)
}
听起来你想要这样的东西。在这里,我们将让useffect监听postCount中的任何更改,以便触发您的逻辑来获取更多的帖子
const Index = (props) => {
const [posts, setPosts] = useState([])
const [postCount, setPostCount] = useState(0)
useEffect(() => {
const getPosts = async () => {
const newPosts= await getPostFromWebService()
setPosts([...posts, newPosts])
}
}, [postCount])
return(
<div>
<button onClick={() => setPostCount(postCount + 5)}>Get more posts</button>
</div>
)
}
const Index=(道具)=>{
const[posts,setPosts]=useState([])
常量[postCount,setPostCount]=useState(0)
useffect(()=>{
const getPosts=async()=>{
const newPosts=wait getPostFromWebService()
setPosts([…posts,newPosts])
}
},[后计数])
返回(
setPostCount(postCount+5)}>获取更多帖子
)
}
可能尝试删除for循环并调用类似于setPosts(posts)
?为每个post调用setPosts感觉像是一个性能问题。@akkonrad:这可能会起作用,但是如果我想再获取5个post,就像分页一样,我想将它们附加到现有的posts上呢?此代码似乎不完整,但是我会这样调用:setPosts([…oldPosts,…fetchedPosts])
可能尝试删除for循环并调用类似于setPosts(posts)
?为每个post调用setPosts感觉像是一个性能问题。@akkonrad:这可能会起作用,但是如果我再获取5个posts,就像分页一样,我想把它们附加到现有的帖子中?这段代码似乎不完整,但我会这样调用:setPosts([…oldPosts,…fetchedPosts])