简体   繁体   English

状态更改后功能组件不会重新渲染

[英]Functional component is not rerendering after state is changed

I would like to ask why my component is not rerendering after my state is changed and I need to refresh it (switch between routes) to see changes.我想问一下为什么我的组件在我的状态改变后没有重新渲染,我需要刷新它(在路由之间切换)才能看到变化。 Well, the interesting fact is that the first time when I click the delete button page (component) does not rerender but after I switch routes and come back the item is deleted and when I try to delete other items, it gets deleted instantly not like the first time.好吧,有趣的事实是,当我第一次单击删除按钮页面(组件)时不会重新渲染,但是在我切换路线并返回后,该项目被删除,当我尝试删除其他项目时,它会立即被删除,不像第一次。

This is my code:这是我的代码:

import React, {useEffect, useState} from 'react';
import ApiFactory from '../mock';
import Editor from '../Editor';
import ProductCard from '../components/product-card/product-card';
import ProductEdit from '../components/product-edit/product-edit';

export default function Admin() {
  const [items, setItems]= useState([]);
  useEffect(() => {
    getProducts();

  }, [items]);

  function getProducts() {
    ApiFactory.getInstance().get('/api/products')
      .then((res) => {
        if(res.status == 200) {
          setItems(res.data);     
        }
      })
      .catch((error) => { console.log(error)}) 
  }

  function handleDelete (productId) {
    ApiFactory.getInstance().delete(`/api/products/${productId}`)
     .then(()=> getProducts()
    );
  }

  return (
    <>
     {
      items.map((item, index) => {
        console.log(item.id)
        return <>
          <div key={index}>
            <ProductCard product={item}></ProductCard>
            <button onClick={() => handleDelete(item.id)}>Delete</button>
          </div>
          </>
      }) 
    }
    </>
  );
}

I am quite new in React can anybody explain why it happens and how can I fix it?我是 React 的新手,谁能解释为什么会发生这种情况,我该如何解决?

I believe it's because of how you have useEffect set up.我相信这是因为您如何设置 useEffect 。

  1. change the useEffect to only make the GET API call once (on initial load):将 useEffect 更改为仅进行一次 GET API 调用(在初始加载时):

     useEffect(() => { getProducts(); }, []); // remove the dependency here. You may have made an infinite loop here. const getProducts = () => { ApiFactory.getInstance().get('/api/products') .then((res) => { if(res.status == 200) { setItems(res.data); } }) .catch((error) => { console.log(error)}) }

If you confirmed that the API call is handling your errors / successes (are you getting non 200 status codes ? those may not be handled)如果您确认 API 调用正在处理您的错误/成功(您是否收到非 200 状态代码?这些可能无法处理)

  1. Add error catching to handleDelete to make sure this call works.将错误捕获添加到 handleDelete 以确保此调用有效。

     const handleDelete = (productId) => { ApiFactory.getInstance().delete(`/api/products/${productId}`) .then(getProducts()) ).catch((error) => { console.log(error)}) }

You may additionally do as another user suggested and move even more logic away from the API calls (not required though) to have state locally and not re-fetch data from the API.您还可以按照另一位用户的建议进行操作,并将更多逻辑从 API 调用中移开(虽然不是必需的),以便在本地拥有状态而不是从 API 重新获取数据。

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

相关问题 如何在功能组件中更改其他 state 后才更改一个 state? - How to make one state change only after other state has been changed in functional component? 组件不会在状态更改时重新呈现? - Component not rerendering on state change? 为什么我的组件在表单提交和使用Firebase设置状态后没有重新渲染? - Why is my component not rerendering after form submission and setting state with Firebase? 在 state 更改后反应组件未重新渲染,但正在调用 render() - React component not rerendering after state change, but render() is being called 尽管使用了 setState(),但在 state 更改后反应组件未重新渲染 - React component not rerendering after state change despite using setState() 在对象数组中添加/删除设置/存储在 state 中的列时,功能组件数据表不重新呈现 - Functional component data table not rerendering when add/remove columns which is set/stored in state in an array of objects Redux State 更改但组件未重新渲染 - Redux State changes but component not rerendering 反应集 state 不重新渲染组件 - react set state not rerendering component 一旦功能组件中的状态发生变化,如何触发钩子? - How to trigger a hook once a state has changed in a functional component? state 更改后反应不重新渲染 - react not rerendering after state change
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM