React Redux Action.js如何整合多API调用,仅在Controller调用统一接口?
解决方案步骤
第一步:在LoopBack4后端创建聚合API接口
既然实际种植数据关联User和State,直接在后端做关联查询,返回聚合后的完整数据,避免前端多次调用接口导致的同步问题。
1.1 修改实际种植模型的Repository
在actual-planting.repository.js中添加关联查询方法,拉取关联的User和State数据:
// actual-planting.repository.js async findWithRelations(filter = {}) { return this.find({ ...filter, include: [ { relation: 'user' }, // 替换为实际种植模型与User的关联名称 { relation: 'state' } // 替换为实际种植模型与State的关联名称 ] }); }
1.2 在实际种植Controller中新增聚合接口
// actual-planting.controller.js @get('/actual-plantings-with-relations', { responses: { '200': { description: '包含关联User和State的实际种植数据列表', content: { 'application/json': { schema: { type: 'array', items: getModelSchemaRef(ActualPlanting, { includeRelations: true }) }, }, }, }, }, }) async findWithRelations( @param.filter(ActualPlanting) filter?: Filter<ActualPlanting>, ): Promise<ActualPlanting[]> { return this.actualPlantingRepository.findWithRelations(filter); }
后端现在会提供一个统一接口,直接返回包含关联数据的实际种植列表。
第二步:前端React Redux封装统一Action
在action.js中创建调用聚合接口的action,替代之前多个API的调用逻辑:
// action.js export const fetchActualPlantingsWithRelations = () => async (dispatch) => { try { dispatch({ type: 'FETCH_PLANTINGS_REQUEST' }); const response = await fetch('/api/actual-plantings-with-relations'); // 替换为你的实际接口路径 const data = await response.json(); dispatch({ type: 'FETCH_PLANTINGS_SUCCESS', payload: data }); } catch (error) { dispatch({ type: 'FETCH_PLANTINGS_FAILURE', payload: error.message }); } };
第三步:在Controller组件中调用统一Action
现在只需要在你的React控制器组件中调用这个单一action,无需再分别调用User和State的API:
// controller.js(React组件) import { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { fetchActualPlantingsWithRelations } from './action'; const ActualPlantingController = () => { const dispatch = useDispatch(); const plantings = useSelector(state => state.plantings.data); const loading = useSelector(state => state.plantings.loading); const error = useSelector(state => state.plantings.error); useEffect(() => { dispatch(fetchActualPlantingsWithRelations()); }, [dispatch]); // 处理删除操作后的刷新:比如删除State成功后重新拉取数据 const handleDeleteState = async (stateId) => { try { await fetch(`/api/states/${stateId}`, { method: 'DELETE' }); dispatch(fetchActualPlantingsWithRelations()); } catch (err) { console.error('删除失败:', err); } }; // 渲染逻辑 if (loading) return <div>加载中...</div>; if (error) return <div>错误:{error}</div>; return ( <div> {plantings.map(planting => ( <div key={planting.id}> <p>种植名称:{planting.name}</p> <p>所属用户:{planting.user?.name}</p> <p>状态:{planting.state?.status}</p> <button onClick={() => handleDeleteState(planting.state.id)}>删除状态</button> </div> ))} </div> ); }; export default ActualPlantingController;
第四步:处理删除后的视图同步
不管是删除User还是State数据,在删除操作完成后,立即调用fetchActualPlantingsWithRelations action重新拉取聚合数据,确保视图能同步更新最新的关联状态。
内容的提问来源于stack exchange,提问作者Nisha
相关产品推荐
相关产品推荐

