ReactJS - 道具未传递给组件

问题描述 投票:0回答:1

我创建了一个项目,其中的组件显示员工列表。

MyEmployee 组件:

import { useState } from "react";

export default function MyEmployee({
  data = [],
  page = 1,
  size = 2,
  total = 0
}) {
  const [myEmployees, setMyEmployees] = useState(data);
  const [currPage, setCurrPage] = useState(page);
  const [rows, setRows] = useState(size);
  const [totalData, setTotalData] = useState(total);

  return (
    <>
      {console.log("data: ", data)}
      {console.log("myEmployees: ", myEmployees)}
      <h2>Some Employee</h2>
      {myEmployees.map((emp) => {
        console.log("iterate emp", emp);
        return (
          <div key={emp.id}>
            <span>{emp.name}</span>
            <span>{emp.email}</span>
          </div>
        );
      })}
      <button>{"<"}</button>
      <span>
        {currPage} of {Math.ceil(totalData / rows)}
      </span>
      <button>{">"}</button>
    </>
  );
}

然后在应用程序组件中我传递道具:

import { useEffect, useState } from "react";
import MyEmployee from "./MyEmployee";
import { getSomeData } from "./SomeService";

export default function App() {
  const [employees, setEmployees] = useState({});

  function getData() {
    const emp = getSomeData();
    console.log("emp: ", emp);
    if (emp?.status) {
      setEmployees(emp.data);
    }
    console.log("employees: ", employees);
  }

  useEffect(() => {
    getData();
  }, []);

  return (
    <div className="App">
      {console.log("employees: ", employees)}
      <MyEmployee
        data={employees?.someEmployeeData?.obj}
        page={employees?.someEmployeeData?.page}
        size={employees?.someEmployeeData?.size}
        total={employees?.someEmployeeData?.total}
      />
    </div>
  );
}

道具来自 SomeService.js:

export function getSomeData() {
  return {
    status: true,
    message: null,
    data: {
      someEmployeeData: {
        page: 1,
        size: 2,
        total: 5,
        obj: [
          {
            id: 1,
            name: "Deas",
            email: "[email protected]"
          },
          {
            id: 2,
            name: "Joey",
            email: "[email protected]"
          }
        ]
      }
    }
  };
}

但是我看到道具没有传递,因为用道具初始化的 MyEmployee 中的状态具有默认值。我错过了什么/做错了什么?

代码沙盒

reactjs react-props
1个回答
0
投票

您正在传递 props,但没有在组件内设置状态,因为您希望它们位于不同的变量中。试试这个

MyEmployee.js

const [myEmployees, setMyEmployees] = useState(data);
const [currPage, setCurrPage] = useState(page);
const [rows, setRows] = useState(size);
const [totalData, setTotalData] = useState(total);

useEffect(() => {
  setMyEmployees(data);
  setCurrPage(page);
  setRows(size);
  setTotalData(total);
}, [data, page, size, total]);


return (
  etc...
© www.soinside.com 2019 - 2024. All rights reserved.