首页 > 解决方案 > 使用 React-Table 和 Fetch GET JSON 创建包含列的动态表

问题描述

嗨,React 新手,我正在尝试使用 React-Table 创建一个表,其中包含通过获取响应使用 JSON 数据的自动列。

我有一个基于 fetch get 创建的表的示例

componentDidMount(){
    const url = 'https://jsonplaceholder.typicode.com/posts/';
    fetch(url,{
      method: "GET"
    }).then(response => response.json()).then(result => {
      this.setState({posts: result })
    })
  }

但是,您需要指定访问器,这对于大型数据集并不实用。这是它的代码沙箱:https ://codesandbox.io/embed/goofy-dew-u94bu

我有另一个带有自动列的表示例,但是,JSON 是硬编码的,所以我不知道如何使用 fetch 响应将其分配给全局以使其“硬编码”,因为它是异步的。

这是它的代码沙箱。 https://codesandbox.io/s/static-fnn42

在此示例中,它成功地根据 initial_data 创建了表,但是,当我取消注释 componenetDidMount 并将“this.state.initial_data”替换为“this.state.posts”时出现错误

class App extends React.Component {
constructor(props){
  super(props);
  this.state = {
    posts: [],
    value: '',
    initial_data: [
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
]
  }
}

/*
componentDidMount(){
  const url = 'https://jsonplaceholder.typicode.com/posts';
  fetch(url,{
    method: "GET"
  }).then(response => response.json()).then(posts => {
    this.setState({posts: response.posts})
  })
}
*/


getColumns() {
  return Object.keys(this.state.initial_data[0]).map(key => {
    return {
      Header: key,
      accessor: key
    };
  });
}

render() {
  const columns = this.getColumns();
 // console.log(JSON.stringify(this.state.initial_data));
  return (
    <div>
      <ReactTable
        data={this.state.initial_data}
        columns={columns}
        defaultPageSize={10}
        className="-striped -highlight"
        filterable
      />
      <br />
    </div>
  );
}
}

ReactDOM.render( <
App / > ,
document.getElementById('app')
);
  </script>
</body>
</html>

在下面的函数中,将“this.state.initial_data”替换为“this.state.posts[0]”时出现错误,它说对象为NULL,这可能是因为一旦它超出了FETCH get,数据因为未定义基于它的异步性质。如果是,我该如何绕过这个?

getColumns() {
    return Object.keys(this.state.initial_data[0]).map(key => {
      return {
        Header: key,
        accessor: key
      };
    });

我也认为“posts:[]”的状态也存在问题,因为当我记录它时,它显示[],然后是[object],对于​​硬编码的示例,它只显示[Object]。

我对其他解决方案/库持开放态度以使其发挥作用。如果您可以在代码沙箱、jsfiddle、codepen 等中找到您的解决方案,那就太棒了!谢谢!!

标签: javascriptreactjsfetchreact-table

解决方案


您需要在您的getColumns()方法中添加一个条件,以便Object.keys仅在this.state.posts[0]有一些数据时执行 -

  getColumns() {
    const getPostKeys = this.state.posts[0];
    if (getPostKeys) {
      const column =
        this.state.posts &&
        Object.keys(getPostKeys).map(key => {
          return {
            Header: key,
            accessor: key
          };
        });
      return column;
    } else {
      return [];
    }
  }

工作示例 - https://codesandbox.io/s/unruffled-clarke-ln7wx


推荐阅读