reactjs 材料表未显示任何数据

kq0g1dla  于 2023-04-05  发布在  React
关注(0)|答案(2)|浏览(129)

我试图从后端API获取数据并将其Map到表,但没有数据出现。如果我控制台数据,我可以在数组中看到我需要的数据。我将感谢任何帮助,我是React的新手,请原谅。干杯...............................................................................................................................................................................................................................................

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;
};

我会很感激任何提示:)

p3rjfoxz

p3rjfoxz1#

在useEffect中提到的移除依赖项,并且依赖项是函数remove [] empty可以工作

mm5n2pyu

mm5n2pyu2#

在您的代码中,setData从未被调用,因此数据状态始终为[](您为其提供的init值)
如果getAllCustomers返回一个customers数组,也许这样更合适:

// if getAllCustomers is not async
useEffect(() => {
    setData(getAllCustomers())
}, []);

// or getAllCustomers is async
useEffect(() => {
    getAllCustomers()
        .then((myData) => setData(myData))
        .catch((err) => console.error(err));
}, []);

另外,你对useEffect的使用是无效的,setData不应该在dependancies数组中,因为它不会改变。更多关于钩子的信息在这里:https://fr.reactjs.org/docs/hooks-intro.html

相关问题