您好,我正在操作中使用调度: 但出于某种原因,她从未停止发送我的调度我使用了控制台.log在我的回复中,我得到了不间断的
import {FETCH_FAIL,FETCH_LOADING,FETCH_SUCESS} from './actionType';
import api from '../../../services/api';
import { useDispatch } from "react-redux";
const FetchSucess = data => (console.log(data),{
type:FETCH_SUCESS,
data
});
const FetchFailed = error => ({
type:FETCH_FAIL,
error
});
const isLoadingFetch = () => ({type: FETCH_LOADING})
export default function AllProducts () {
const dispatch = useDispatch()
dispatch(isLoadingFetch());
// fetching data
api.get('/products')
.then( response => { dispatch(FetchSucess(response.data))})
.catch( err => { dispatch(FetchFailed(err.message));});
}
和我的容器:
export default function Cards() {
const classes = useStyles();
const classes2 = useStyles2();
const loadProducts = getAllProducts();
const products = useSelector(state => state.data.filteredProducts);
return (
<div className="App">
<Container maxWidth="md" className={classes.root}>
<Grid container md={4} spacing={1} ></Grid>
<Grid container md={8} spacing={1} alignItems={"center"}>
{products.map(product => (
<Grid item lg={4} md={4} sm={12} xs={12}>
<Card className={classes2.card}>
<CardMedia
className={classes2.media}
image={
"https://www.theclutch.com.br/wp-content/uploads/2019/11/skins-csgo-neymar.jpg"
}
/>
<CardContent className={classes2.content}>
<Typography
className={classes2.name}
variant={"h6"}
gutterBottom
>
{product.name}
</Typography>
<Typography
className={classes2.price}
variant={"h1"}
>
{util.formatCurrency(product.price)}
</Typography>
</CardContent>
</Card>
</Grid>
))}
</Grid>
</Container>
</div>
);
}
但是在控制台上.log我的调度不会一直停止运行 我不知道这是否正确 他一直在发送调度,从不发送
我不知道这是否正常,如果有人可以帮助我。
似乎在从 AllProducts(( 加载数据时重新渲染了组件。
const loadProducts = getAllProducts();
这只需要调用一次。 你需要使用 useEffect(并将第二个参数作为空数组传递(,它类似于 componentDidMount。
import React, { useState, useEffect } from 'react';
export default function Cards() {
useEffect(() => {
// This will be invoked only once.
getAllProducts();
}, []);
const classes = useStyles();
const classes2 = useStyles2();
const products = useSelector(state => state.data.filteredProducts);
return (
<div className="App">
<Container maxWidth="md" className={classes.root}>
<Grid container md={4} spacing={1} ></Grid>
<Grid container md={8} spacing={1} alignItems={"center"}>
{products.map(product => (
<Grid item lg={4} md={4} sm={12} xs={12}>
<Card className={classes2.card}>
<CardMedia
className={classes2.media}
image={
"https://www.theclutch.com.br/wp-content/uploads/2019/11/skins-csgo-neymar.jpg"
}
/>
<CardContent className={classes2.content}>
<Typography
className={classes2.name}
variant={"h6"}
gutterBottom
>
{product.name}
</Typography>
<Typography
className={classes2.price}
variant={"h1"}
>
{util.formatCurrency(product.price)}
</Typography>
</CardContent>
</Card>
</Grid>
))}
</Grid>
</Container>
</div>
);
}