【问题标题】:Using React-Table and Fetch GET JSON to create a dynamic table with columns使用 React-Table 和 Fetch GET JSON 创建包含列的动态表
【发布时间】:2019-08-24 20:25:20
【问题描述】:

嗨,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 获取数据,因为未定义基于它的 aync 特性。如果是,我该如何绕过这个?

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

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

我愿意接受其他解决方案/库以使其正常工作。如果您可以在代码沙箱、jsfiddle、codepen 等中找到您的解决方案,那就太棒了!谢谢!!

【问题讨论】:

    标签: javascript reactjs fetch react-table


    【解决方案1】:

    您需要在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

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多