React中.then函数内状态复制失败问题求助
问题分析与解决方法
核心问题原因
React中useState的状态更新是异步的,你在调用setOgposts(res.data)后立刻执行setPosts(ogposts),此时ogposts还没完成更新,依然是初始的空数组,所以posts会被设置为空。
解决方法
有两种可行的修复方式:
方式一:直接使用API返回数据同步两个状态
既然已经拿到了API返回的res.data,可以直接把它同时赋值给两个状态,不需要依赖ogposts的更新:
fetch(restApi) .then(res => res.json()) .then(res => { const userData = res.data; setOgposts(userData); setPosts(userData); })
方式二:通过监听ogposts同步posts
如果业务逻辑需要依赖ogposts的变化来更新posts,可以添加一个专门的useEffect监听ogposts的状态:
// 原有的useEffect保持不变 useEffect(()=>{ const restApi = 'https://reqres.in/api/users/'; fetch(restApi) .then(res=> res.json()) .then(res=> setOgposts(res.data)) },[]) // 新增监听ogposts的useEffect useEffect(() => { setPosts(ogposts); }, [ogposts]); // 当ogposts变化时触发
额外的表格渲染修正
你的表格渲染逻辑存在结构错误,当前写法会把所有用户的ID、姓名等都塞进同一个<td>里,正确的做法是每个用户对应一行<tr>,修正后的代码如下:
return ( <div> <table> <tr> <th> Id </th> <th> FirstName </th> <th> LastName </th> <th> EmailId </th> </tr> {/* 遍历posts生成每一行数据 */} {posts.map((user) => ( <tr key={user.id}> <td>{user.id}</td> <td>{user.first_name}</td> <td>{user.last_name}</td> <td>{user.email}</td> </tr> ))} </table> </div> );
注意给每个<tr>添加唯一的key属性,这是React列表渲染的要求。
内容的提问来源于stack exchange,提问作者Muzammil Ahmed
相关产品推荐
相关产品推荐

