The problem is the clean
variable which is not a part of your component's state. It exists only inside the scope of the useEffect
callback and gets recreated every time that the effect runs.
What is the purpose of clean
and when should we set it to true
? The cleanup function of a useEffect
hook only runs when the component unmounts so that would not be the right place to set a boolean
flag like this.
In order to dispatch once per product, we can eliminate it and just rely on the dependencies array. I'm using product_.id
instead of product
so that it re-runs only if the id changes, but other property changes won't trigger it.
useEffect(() => {
dispatch(listReviewsDetailsByProductId(product._id))
}, [dispatch, product._id])
If this clean
state serves some purpose, then it needs to be created with useState
so that the same value persists across re-renders. You need to figure out where you would be calling setClean
. This code would call the dispatch only once per component even if the product
prop changed to a new product, which is probably not what you want.
const [clean, setClean] = useState(false);
useEffect(() => {
if (!clean) {
dispatch(listReviewsDetailsByProductId(product._id))
setClean(true);
}
}, [dispatch, product._id, clean, setClean])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…