【问题标题】:React treating functional component as an object {Uncaught Error: Objects are not valid as a React child (found: object with keys)React 将功能组件视为对象 {Uncaught Error: Objects are not valid as a React child (found: object with keys)
【发布时间】:2023-01-25 14:45:42
【问题描述】:

我正在尝试渲染一个 Alert 组件,当从父组件将 prop 传递给它时,该组件应该渲染,但我收到错误 Uncaught Error: Objects are not valid as a React child (found: object with keys {message, showAlerts}). If you meant to render a collection of children, use an array instead. 我不确定为什么 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>
  );
}

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

我尝试以我认为可接受的方式呈现警报的子组件。单击按钮时,警报组件必须呈现并且警报框必须打开。在解除警报时,用于显示警报的状态变量 (showAlerts) 也必须在父组件中更改为“false”。

【问题讨论】:

  • 首先,改变这个:export default function AppAlerts(message, showAlerts)到这个export default function AppAlerts({message, showAlerts})

标签: javascript reactjs


【解决方案1】:

改变这个:

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

对此:

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

因为道具始终是一个对象,并且它们(总是)作为第一个参数传递。

在参数列表中使用花括号意味着你正在破坏第一个参数(这是 props 参数)

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2023-01-17
    • 2020-12-09
    • 2020-01-12
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2020-04-14
    相关资源
    最近更新 更多