要实现不同表的条件性API端点React-Redux,可以按照以下步骤进行:
redux
和react-redux
库来实现。import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers'; // 根reducer
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
// src/reducers/tableReducer.js
const initialState = {
table1: [],
table2: [],
// 其他表格的初始状态
};
const tableReducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_TABLE1_SUCCESS':
return {
...state,
table1: action.payload,
};
case 'FETCH_TABLE2_SUCCESS':
return {
...state,
table2: action.payload,
};
// 其他表格的reducer case
default:
return state;
}
};
export default tableReducer;
// src/actions/tableActions.js
export const fetchTable1 = (condition) => async (dispatch) => {
try {
// 根据条件发起API请求
const response = await fetch(`/api/table1/${condition}`);
const data = await response.json();
dispatch({
type: 'FETCH_TABLE1_SUCCESS',
payload: data,
});
} catch (error) {
// 处理错误
console.error(error);
}
};
export const fetchTable2 = (condition) => async (dispatch) => {
try {
// 根据条件发起API请求
const response = await fetch(`/api/table2/${condition}`);
const data = await response.json();
dispatch({
type: 'FETCH_TABLE2_SUCCESS',
payload: data,
});
} catch (error) {
// 处理错误
console.error(error);
}
};
// 其他表格的action
// src/components/Table1.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchTable1 } from '../actions/tableActions';
const Table1 = () => {
const dispatch = useDispatch();
const table1Data = useSelector((state) => state.table1);
useEffect(() => {
// 根据条件获取表格数据
dispatch(fetchTable1('condition'));
}, [dispatch]);
return (
{/* 渲染表格 */}
Column 1
Column 2
{table1Data.map((row) => (
{row.column1}
{row.column2}
))}
);
};
export default Table1;
// src/components/Table2.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchTable2 } from '../actions/tableActions';
const Table2 = () => {
const dispatch = useDispatch();
const table2Data = useSelector((state) => state.table2);
useEffect(() => {
// 根据条件获取表格数据
dispatch(fetchTable2('condition'));
}, [dispatch]);
return (
{/* 渲染表格 */}
Column 1
Column 2
{table2Data.map((row) => (
{row.column1}
{row.column2}
))}
);
};
export default Table2
上一篇:不同表的SQL查询不一致