gpt4 book ai didi

javascript - 在每个渲染上调度 Action

转载 作者:行者123 更新时间:2023-12-02 02:32:12 27 4
gpt4 key购买 nike

我在 ProductList 组件的每次安装上调度操作 addProducts ,而我想使用 useEffect 钩子(Hook)调度一次操作并将数据存储在 redux 中然后使用它。

下面是我的操作文件和 ProductList 组件文件。

actions.js 文件

export const addProducts = () => async (dispatch) => {
let Products = await axios.get("https://api.npoint.io/2a4561b816e5b6d00894");
return dispatch({
type: ADD_PRODUCTS,
payload: Products.data,
});
};

ProductList.js组件文件

import { addProducts } from "../actions/Index";
const ProductList = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(addProducts());
},[]);
const Products = useSelector((state) => state.products);
console.log(Products)

最佳答案

您可以只在组件中分派(dispatch)该操作,但如果产品可用,则在 thunk 操作中不执行任何操作:

export const addProducts = () => async (
dispatch,
getState,//thunk also get a getState function
) => {
//you should write a dedicated selector function so you could do:
// const productsInState = selectProducts(getState())
const productsInState = getState().products
//whatever would make state.products available
// reducers are missing in your question
if(productsInState){
//do nothing if products are already in state
return;
}
let Products = await axios.get(
'https://api.npoint.io/2a4561b816e5b6d00894',
);
return dispatch({
type: ADD_PRODUCTS,
payload: Products.data,
});
};

在你的组件中,你可以只在每个渲染上调度,如果你的页面有多个组件调度此操作,那么你可以创建一个 grouped action

关于javascript - 在每个渲染上调度 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64890923/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com