React hooks - useState() 不会使用新的状态更新重新渲染 UI [英] React hooks - useState() is not re-rendering the UI with the new state updates

查看:29
本文介绍了React hooks - useState() 不会使用新的状态更新重新渲染 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试新的 React Hooks,但我有点卡住了,因为当本地状态更新时 UI 没有更新.这是我的代码,

import React, { useState, useEffect } from 'react';从'./Post'导入帖子从 './PostForm' 导入 PostForm;从 'axios' 导入 axios;函数 PostsList() {const [posts, setPosts] = useState([]);//使用 useEffect 作为 CDM 的替代方法设置本地状态useEffect(() => {axios.get('...').then(res => {//resposne 是一个对象数组setPosts(res.data)})})const handleSubmit = (数据) =>{//我在这里得到的数据是一个与posts数组中的对象格式相同的对象axios.post('...', 数据).then(res => {//记录数据以验证其格式.到目前为止工作正常..控制台日志(res.data);//问题在这里设置帖子([...帖子,资源数据])}).catch(err => console.log(err))}返回 (<div><PostForm handleSubmit={handleSubmit}/><h3>当前帖子</h3>{ post.map(post => (<发布键={post.id} post={post}/>)) }

)}

当我提交表单时,UI 闪烁一瞬间,然后在没有新更新的情况下呈现当前状态,似乎有什么东西阻止了它重新呈现新状态.如果需要更多代码/说明,请在下面发表评论.提前致谢.

解决方案

好的,问题通过@skyboyer 的有用提示解决了,
所以最初发生的事情是,useEffect() 就像 componentDidMount() &componentDidUpdate() 同时,这意味着每当状态有更新时,useEffect() 就会被调用,这意味着随着初始数据的到来重置状态从服务器.为了解决这个问题,我需要使 useEffect() 仅在创建/渲染组件时渲染一次组件,而不是在每次更新状态时渲染它.这是通过向 useEffect() 函数添加一个空数组作为第二个参数来完成的.如下图.

 useEffect(() => {axios.get('...').then(res => {setPosts(res.data)})}, [])

谢谢:)

I am trying out the new React Hooks, and I am a little stuck as the UI is not updating when the local state is updated. Here is my code,

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>
  )
}

when I submit the form, the UI flickers for a split second and then renders the current state without the new update, it seems that something is preventing it from re-rendering the new state. If more code/clarification is needed please leave a comment below. thanks in advance.

解决方案

alright, problem solved with the helpful hint from @skyboyer,
so what happened initially is, the useEffect() acts like componentDidMount() & componentDidUpdate() at the same time, that means whenever there is an update to the state, the useEffect() gets invoked, which means resetting the state with the initial data coming from the server. to fix the issue I needed to make the useEffect() renders the component only one time when it's created/rendered as opposed to rendering it every time there is an update to the state. and this is done by adding an empty array as a second argument to the useEffect() function. as shown below.

 useEffect(() => {
   axios.get('...')
    .then(res => {
      setPosts(res.data)
     })
   }, [])

thanks :)

这篇关于React hooks - useState() 不会使用新的状态更新重新渲染 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆