React Redux新手求教:Redux Thunk参数传递与产品数据更新问题
解决React Redux传递多参数API请求及参数变更更新数据问题
你的Thunk代码已经做好了接收exportCountryId和categoryId的准备,接下来按以下步骤完成整个流程:
1. 在组件中传递参数调用Thunk
在需要获取产品的组件里,通过useDispatch钩子触发productsFetch,直接传入包含两个参数的对象即可:
import { useDispatch } from 'react-redux'; import { productsFetch } from './path/to/your/thunk'; // 假设你从props或状态中拿到这两个参数 const [exportCountryId, setExportCountryId] = useState('1'); const [categoryId, setCategoryId] = useState('2'); const dispatch = useDispatch(); // 触发请求的函数 const fetchProducts = () => { dispatch(productsFetch({ exportCountryId, categoryId })); };
2. 创建Slice处理异步请求状态
你需要一个Redux Slice来管理产品数据的状态,处理Thunk的三种状态(pending/fulfilled/rejected):
import { createSlice } from '@reduxjs/toolkit'; import { productsFetch } from './productsThunk'; const initialState = { items: [], loading: false, error: null, }; const productsSlice = createSlice({ name: 'products', initialState, reducers: {}, extraReducers: (builder) => { builder // 请求中 .addCase(productsFetch.pending, (state) => { state.loading = true; state.error = null; }) // 请求成功 .addCase(productsFetch.fulfilled, (state, action) => { state.loading = false; state.items = action.payload; }) // 请求失败 .addCase(productsFetch.rejected, (state, action) => { state.loading = false; state.error = action.error.message || '获取产品失败'; }); }, }); export default productsSlice.reducer;
别忘了把这个reducer注册到Redux Store里。
3. 监听参数变化自动重新请求
用useEffect钩子监听categoryId和exportCountryId的变化,一旦参数变更就自动触发请求:
import { useEffect } from 'react'; // 在组件内部 useEffect(() => { // 当两个参数都存在时才发起请求(避免空参数调用API) if (exportCountryId && categoryId) { dispatch(productsFetch({ exportCountryId, categoryId })); } }, [dispatch, exportCountryId, categoryId]); // 依赖项包含两个参数,变化时触发
4. 在组件中使用产品数据
通过useSelector获取Store中的产品状态,处理加载和错误情况:
import { useSelector } from 'react-redux'; const { items: products, loading, error } = useSelector((state) => state.products); // 渲染部分 if (loading) return <div>加载中...</div>; if (error) return <div>错误:{error}</div>; return ( <div> {products.map((product) => ( <div key={product.id}>{product.name}</div> ))} </div> );
这样设置后,当categoryId或者exportCountryId变更时,useEffect会自动触发新的API请求,更新Store中的产品数据,组件也会随之重新渲染最新数据。
内容的提问来源于stack exchange,提问作者MHD Firass Barakat
相关产品推荐
相关产品推荐

