MoS*_*lam 5 javascript reactjs react-hooks
我正在尝试新的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>
)
}Run Code Online (Sandbox Code Playgroud)
当我提交表单时,UI会闪烁一秒钟,然后呈现当前状态而不进行新的更新,似乎是某种原因阻止了它重新呈现新状态。如果需要更多代码/说明,请在下面留下评论。提前致谢。
好吧,问题通过@skyboyer 的有用提示解决了,
所以最初发生的事情是,同时useEffect()像componentDidMount()&这样的行为componentDidUpdate(),这意味着每当状态更新时,useEffect()就会调用它,这意味着用初始状态重置状态来自服务器的数据。为了解决这个问题,我需要在useEffect()创建/渲染组件时只渲染一次组件,而不是在每次更新状态时渲染它。这是通过向useEffect()函数添加一个空数组作为第二个参数来完成的。如下所示。
useEffect(() => {
axios.get('...')
.then(res => {
setPosts(res.data)
})
}, [])Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6344 次 |
| 最近记录: |