React中Material Table无法展示后端API数据问题求助
Material Table无法渲染API获取的数据
我尝试从后端API获取数据并映射到Material Table中,但表格未显示任何数据。控制台打印data时能看到所需的数组数据,我是React新手,希望能得到帮助。
相关代码
Customers组件
import { getAllCustomers } from "../../../../features/customers/customerSlice"; const [data, setData] = useState(); const fetchInfo = () => { dispatch(getAllCustomers()); }; useEffect(() => { fetchInfo(); }, [setData]); console.log(data); const columns = [ { title: "ID", field: "id" }, { title: "Username", field: "username" }, { title: "Name", field: "name" }, { title: "Email", field: "email" }, { title: "Phone", field: "phone" }, { title: "Web Link", field: 'website' } ] return ( <CardBody> <ThemeProvider theme={defaultMaterialTheme}> <MaterialTable title="Employee Data" data={data} columns={columns} /> </ThemeProvider> </CardBody> ); }; export default Customers;
customerSlice.jsx
const initialState = { customer: [], autoCustomer: [], customers: [], isLoading: false, isError: false, isSuccess: false, message: "", }; // Get all customers export const getAllCustomers = createAsyncThunk( "customer/getAllCustomers", async (_, thunkAPI) => { try { const token = thunkAPI.getState().auth.user.token; return await customerService.getAllCustomers(token); } catch (error) { const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString(); return thunkAPI.rejectWithValue(message); } } );
customerService.jsx
const getAllCustomers = async (token) => { const config = { headers: { Authorization: `Bearer ${token}`, }, }; const response = await axios.get( "http://localhost:8000/api/v1/customer/paginate-customer", config ); return response.data; };
解决方案
1. 从Redux Store获取数据
你仅触发了获取数据的action,但未从Redux store中读取返回的customers数据。需用useSelector订阅store中的数据:
import { useSelector, useDispatch } from 'react-redux'; // 确保导入这两个hook // 组件内部添加: const { customers, isLoading } = useSelector(state => state.customer);
2. 修正useEffect的依赖
你的useEffect依赖setData会导致组件重复触发请求,应改为依赖dispatch或空数组(只执行一次):
useEffect(() => { fetchInfo(); }, [dispatch]); // 替换[setData]为[dispatch]
3. 同步数据到表格
方案一:直接传递store数据给表格
<MaterialTable title="Employee Data" data={customers} // 直接使用store中的customers columns={columns} isLoading={isLoading} // 可选:添加加载状态提示 />
方案二:更新本地state
添加useEffect监听customers变化,同步到本地state:
useEffect(() => { setData(customers); }, [customers]);
4. 处理API返回的分页数据
你的API接口是paginate-customer,返回的可能是分页格式(比如{ data: [...], total: 10 }),需在slice中正确处理返回结果:
// 在customerSlice的extraReducers中添加: extraReducers: (builder) => { builder .addCase(getAllCustomers.pending, (state) => { state.isLoading = true; }) .addCase(getAllCustomers.fulfilled, (state, action) => { state.isLoading = false; state.isSuccess = true; // 若API返回带data字段的对象,取action.payload.data;否则直接赋值 state.customers = action.payload.data || action.payload; }) .addCase(getAllCustomers.rejected, (state, action) => { state.isLoading = false; state.isError = true; state.message = action.payload; state.customers = []; }); }
5. 确认字段匹配
确保API返回的对象字段名与columns中的field完全一致(比如id、username等),若字段名不匹配需调整映射关系。
内容的提问来源于stack exchange,提问作者user21543876
相关产品推荐
相关产品推荐

