我遇到一个问题,当我调用我传递的刷新函数时,我的页面没有刷新。
function ProductsPage(props) {
const [products, setProduct] = useState([])
const [shouldRefresh, setRefresh] = useState(false)
function refreshProducts() {
setRefresh(!shouldRefresh)
}
const token = localStorage.getItem("token")
const headers = { Authorization: "Token " + token }
useMemo(() => (axios.get("/products", { headers: headers }).then((resp) => (
setProduct(resp.data)
))
), shouldRefresh)
return (
<Box className="cardDeck">
<Redirect_if_not_logged_in />
{products.map((product) => (
<InfoCard product={product} refresh={refreshProducts}></InfoCard>
)).reverse()}
</Box>
)
}
每当我从 InfoCard 调用 props.refresh()
时,什么也没有发生。
最佳答案
您需要使用 useEffect Hook 而不是 useMemo
function ProductsPage(props) {
const [products, setProduct] = useState([]);
const [shouldRefresh, setRefresh] = useState(false);
function refreshProducts() {
setRefresh(!shouldRefresh);
}
const token = localStorage.getItem("token");
const headers = {
Authorization: "Token " + token,
};
useEffect(() => {
axios
.get("/products", {
headers: headers,
})
.then((resp) => setProduct(resp.data));
}, [shouldRefresh]);
return (
<Box className="cardDeck">
<Redirect_if_not_logged_in />
{products
.map((product) => (
<InfoCard product={product} refresh={refreshProducts}></InfoCard>
))
.reverse()}
</Box>
);
}
关于reactjs - React 组件不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69868003/