首页 > 解决方案 > React Router 从 API 获取数据

问题描述

我是新手,现在正在开发一个必须从 API 获取一些数据的应用程序。

我的组件应该获取数据并返回一个 Json 对象并填充一个表。

      class RenderTable() extends React.Component {
    render() {
      fetch("http://localhost:6002/api?act=getall")
     .then(data=> data.json())
     .then(
       result => {
       this.setState({
        library: result
      });
        console.log(this.state.result);
    },
    error => {
      this.setState({
        library: "error"
      });
      return null;
    }
  );
}

render() {
return (
  <div id="libTable">
    <table>
      <tbody>
        <tr>
          <th>Genre</th>
          <th>Description</th>
          <th>Date</th>
          <th>Price</th>
        </tr>
        <tr>
          <td>{JSON.stringify(this.state.library)}</td>
        </tr>
      </tbody>
    </table>
  </div>
);

} }

 <Route path="/RenderTable" component={RenderTable} />

我的库是一个数组,我在我的主应用程序容器中初始化为一个空数组。路由路径在我的主应用程序中的渲染下。任何帮助深表感谢。

标签: jsonajaxreactjsapirouter

解决方案


在 render 方法中映射您的状态,如下所示:

return (
  <div id="libTable">
    <table>
      <tbody>
        <tr>
          <th>Genre</th>
          <th>Description</th>
          <th>Date</th>
          <th>Price</th>
        </tr>
        {this.state.library.map(book => (
          <tr>
            <td>{book.genre}</td>
            <td>{book.description}</td>
            <td>{book.date}</td>
            <td>{book.price}</td>
          </tr>
          ))}
      </tbody>
    </table>
  </div>
);

您的类组件中还有一些其他奇怪的错误,例如 2 个渲染方法。一个可能的正确实现如下所示:

class RenderTable extends React.Component {
  state = {
    library: [],
    error: ""
  };

  componentDidMount() {
    fetch("http://localhost:6002/api?act=getall")
      .then(data => data.json())
            .then(result => {
        this.setState({
          library: result
        });
        console.log(this.state.result);
      })
      .catch(error =>
        this.setState({
          error
        })
      );
  }

  render() {
    return (
      <div id="libTable">
        <table>
          <tbody>
            <tr>
              <th>Genre</th>
              <th>Description</th>
              <th>Date</th>
              <th>Price</th>
            </tr>
            {this.state.library.map(book => (
              <tr>
                <td>{book.genre}</td>
                <td>{book.description}</td>
                <td>{book.date}</td>
                <td>{book.price}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}


推荐阅读