繁体   English   中英

React hooks - useState()不会使用新的状态更新重新呈现UI

[英]React hooks - useState() is not re-rendering the UI with the new state updates

我正在尝试新的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) }) }, []) 
谢谢 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM