[英]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 。
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 状态代码?这些可能无法处理)
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.