json defaultExpandAllRows antd表React,获取不工作

x33g5p2x  于 2023-07-01  发布在  React
关注(0)|答案(2)|浏览(151)

我使用Ant设计表作为用户界面
我的代码出了什么问题,使用本地数据的表可以自动扩展,但这是不同的,因为fetch的结果不能自动扩展相同的代码
我错过了什么?
我无法用好的语言解释,看看我的沙盒https://codesandbox.io/s/defaultexpandallrows-antd-table-f1okb
此代码将自动展开

const data = [
  {
    key: 55,
    name: "John Brown sr.",
    xchildren: [
      { key: 73, address: "New York No. 2 Lake Park" },
      { key: 46, address: "New York No. 2 Lake Park" },
    ],
  },
];

 <Table
      dataSource={data}
      defaultExpandAllRows={true}
      key={data.key}
      expandable={{
        expandedRowRender: (record) => (
          <Table pagination={false} dataSource={record.xchildren}>
            <Column title="Address" dataIndex="address" key="address" />
          </Table>
        ),
      }}
    >
      <Column title="name" dataIndex="name" key="key" />
    </Table>

这将不会自动展开表

fetch = () => {
    fetch(`https://api.jsonbin.io/b/61e6fd62ba87c130e3eaa7ef`)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        this.setState({
          dataJSON: data,
        });
      });
  };

  <Table
           <Table
      dataSource={dataJSON}
      defaultExpandAllRows={true}
      key={data.key}
      expandable={{
        expandedRowRender: (record) => (
          <Table dataSource={record.xchildren}>
            <Column
              pagination={false}
              title="Address"
              dataIndex="address"
              key="address"
            />
          </Table>
        ),
      }}
    >
      <Column title="name" dataIndex="name" key="key" />
    </Table>

全码

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Table,version } from "antd";
const { Column } = Table;

const data = [
  {
    key: 55,
    name: "John Brown sr.",
    xchildren: [
      { key: 73, address: "New York No. 2 Lake Park" },
      { key: 46, address: "New York No. 2 Lake Park" },
    ],
  },
];

class App extends React.Component {
  state = {
    dataJSON: [],
  };

  componentDidMount() {
    const { pagination } = this.state;
    this.fetch({ pagination });
  }

  fetch = () => {
    fetch(`https://api.jsonbin.io/b/61e6fd62ba87c130e3eaa7ef`)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        this.setState({
          dataJSON: data,
        });
      });
  };

  render() {
    const { dataJSON } = this.state;
    return (
      <>
      antd version: {version}
      <p>will automatically expand</p>
        <Table
          dataSource={data}
          defaultExpandAllRows={true}
          key={data.key}
          expandable={{
            expandedRowRender: (record) => (
              <Table pagination={false} dataSource={record.xchildren}>
                <Column title="Address" dataIndex="address" key="address" />
              </Table>
            ),
          }}
        >
          <Column title="name" dataIndex="name" key="key" />
        </Table>
        <hr />
        <p> will not automatically expand</p>
        <Table
          dataSource={dataJSON}
          defaultExpandAllRows={true}
          key={data.key}
          expandable={{
            expandedRowRender: (record) => (
              <Table dataSource={record.xchildren}>
                <Column
                  pagination={false}
                  title="Address"
                  dataIndex="address"
                  key="address"
                />
              </Table>
            ),
          }}
        >
          <Column title="name" dataIndex="name" key="key" />
        </Table>
      </>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("container"));
z9ju0rcb

z9ju0rcb1#

你的问题是因为你的dataJSON在第一次渲染中是空的,所以antd不能识别哪些行应该在下一次渲染中扩展,要解决这个问题有几个解决方案:
1-仅当dataJSON已填充时才呈现表,如下所示:

{dataJSON.length > 0 ? <Table
      dataSource={dataJSON}
      defaultExpandAllRows={true}
      key={data.key}
      expandable={{
        expandedRowRender: (record) => (
          <Table dataSource={record.xchildren}>
            <Column
              pagination={false}
              title="Address"
              dataIndex="address"
              key="address"
            />
          </Table>
        )
      }}
    >
      <Column title="name" dataIndex="name" key="key" />
    </Table> : 'loading...'}

2-在expandable配置中通过expandedRowKeys属性控制扩展行,如下所示:

<Table
      dataSource={dataJSON}
      defaultExpandAllRows={true}
      key={data.key}
      expandable={{
        expandedRowKeys: dataJSON.map(o => o.key),
        expandedRowRender: (record) => (
          <Table dataSource={record.xchildren}>
            <Column
              pagination={false}
              title="Address"
              dataIndex="address"
              key="address"
            />
          </Table>
        )
      }}
    >
      <Column title="name" dataIndex="name" key="key" />
</Table>
bn31dyow

bn31dyow2#

您可以使用自定义钩子:

import { useEffect, useState } from 'react';

const useExpandedRowsControl = <T extends {key: string}, >({ tableData }:
  {tableData: T[] | undefined}) => {
  const [expandedRowKeys, setExpandedRowKeys] = useState<ReadonlyArray<string>>([]);

  const onExpand = ((flag: boolean, record: T) => {
    setExpandedRowKeys((prev) => {
      if (flag) {
        return [...prev, record?.key];
      }

      if (!flag) {
        return prev.filter((key) => key !== record?.key);
      }

      return [];
    });
  });

  useEffect(() => {
    setExpandedRowKeys(tableData?.map((o) => o?.uuid) || []);
  }, [tableData]);

  return {
    expandedRowKeys, onExpand,
  };
};

export default useExpandedRowsControl;

带工作台的组件:

...
const { expandedRowKeys, onExpand } = useExpandedRowsControl({ tableData: tableData });
    
return (
  <Table
    columns={columns}
    dataSource={dataSource}
    expandable={{ expandedRowKeys, onExpand }}
  />
);
...

相关问题