处理将函数组件作为对象的反应时出现的错误:对象不是有效的React子元素(找到:带有键的对象)
P粉548512637
P粉548512637 2023-09-10 11:59:55
0
1
663

我正在尝试渲染一个Alert组件,当一个prop从父组件传递给它时,它应该渲染,但是我遇到了一个错误

未捕获的错误:对象不是有效的React子元素(找到:具有键{message,showAlerts}的对象。如果您想要渲染一个子元素集合,请使用数组代替。

我不确定为什么React将我的函数组件视为对象。代码沙盒链接:https://codesandbox.io/s/exciting-smoke-mij6ke?file=/src/App.js:0-3054

这是父组件:

import styled from "styled-components";
import { useTable } from "react-table";
import Alert from "react-bootstrap/Alert";
import Button from "react-bootstrap/Button";
import axios from "axios";

import AppAlerts from "./components/Alerts";

const Styles = styled.div`
  padding: 1rem;

  table {
    border-spacing: 0;
    border: 1px solid black;

    tr {
      :last-child {
        td {
          border-bottom: 0;
        }
      }
    }

    th,
    td {
      margin: 0;
      padding: 0.5rem;
      border-bottom: 1px solid black;
      border-right: 1px solid black;

      :last-child {
        border-right: 0;
      }
    }
  }
`;

function Table({ columns, data }) {
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

  const [showAlert, setShowAlert] = useState(false);
  const [alertMessage, setAlertMessage] = useState("");
  const handleButttonClick = () => {
    setShowAlert(true);
    setAlertMessage("dummy text");
  };

  // Render the UI for table
  return (
    <div>
      <div>
        <AppAlerts message={alertMessage} showAlerts={showAlert} />;
      </div>

      <table {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps()}>{column.render("Header")}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
      <Button onClick={handleButttonClick}>Open Alert box</Button>
    </div>
  );
}

function App() {
  // const [data, setData] = useState([]);
  // const [columns, setColumns] = useState([]);

  const columns = React.useMemo(
    () => [
      { Header: "Id", accessor: "id" },
      { Header: "Applicant", accessor: "applicant" },
      { Header: "Pincode", accessor: "pincode" },
      { Header: "District", accessor: "district" },
      { Header: "State", accessor: "state" }
    ],
    []
  );
  const data = React.useMemo(
    () => [
      {
        id: 18,
        applicant: "Buzz",
        pincode: 560096,
        district: 1,
        state: 1
      },
      {
        id: 19,
        applicant: "Sue",
        pincode: 560100,
        district: 2,
        state: 1
      }
    ],
    []
  );

  return (
    <div className="App">
      <Styles>
        <Table columns={columns} data={data} />
      </Styles>
    </div>
  );
}

export default App;

子组件:

import { useEffect, useState } from "react";
import Alert from "react-bootstrap/Alert";

export default function AppAlerts(message, showAlerts) {
  const [show, setShow] = useState(showAlerts);

  return (
    <Alert
      variant="info"
      onClose={() => setShow(false)}
      show={show}
      dismissible
    >
      <p>{message}</p>
    </Alert>
  );
}

我在这里做错了什么,我应该改变什么?

我尝试以我认为被接受的方式渲染Alerts的子组件。点击按钮后,Alert组件必须渲染并打开警报框。在关闭警报时,父组件中显示警报的状态变量(showAlerts)也必须更改为'false'。

P粉548512637
P粉548512637

全部回复(1)
P粉492959599

将下面这句话翻译成中文,保留html代码,不用增加新内容:

export default function AppAlerts(message, showAlerts) { ... }

变成:

export default function AppAlerts({message, showAlerts}) { ... }

因为props总是一个对象,并且它们作为第一个参数传递。

在参数列表中使用花括号意味着你正在解构第一个参数(即props参数)。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板