【问题标题】:PHP, MySQL, React, Rest API tutorial confusion Part 2PHP、MySQL、React、Rest API 教程混淆 Part 2
【发布时间】:2020-09-07 08:40:15
【问题描述】:

仍然遵循以下教程:

https://www.techiediaries.com/php-react-rest-api-crud-tutorial/

我终于在控制台中没有错误。但是我在控制台中得到的只是一个空白数组,它只是读取 [ ]

完整代码如下:

<script type="text/babel">
  class App extends React.Component {
  componentDidMount() {
    const url = 'api/testQuery.php'
    axios.get(url).then(response => response.data)
    .then((data) => {
     this.setState({ users: data })
     console.log(this.info.users)
   })
  }
  info = {
   users: []
  } 
  render() {
   return (
    <React.Fragment>
    <h1>All Users</h1>
    <table border='1' width='100%'>
    <tr>
      <th>Username</th>
      <th>Fullname</th>
      <th>Email</th>
    </tr>

    {this.info.users.map((user) => (
      <tr>
        <td>{ user.username }</td>
        <td>{ user.fullname }</td>
        <td>{ user.email }</td>
      </tr>
    ))}
    </table>
    </React.Fragment>
   );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script>

从 testQuery.php 脚本返回的 json 如下所示:

[
  {
    "uid":"7",
    "username":"tna.mjordan",
    "fullname":"Michael Jordan",
    "email":"tna.mjordan@tna.com",
    "userlevel":"9",
    "division":"Chicago"
  }, 
  // and so on
]

关于为什么我得到一个空白用户数组以及如何解决它的任何想法?

【问题讨论】:

  • 您的 console.log 语句是 this.info.users。这是在哪里设置的?您的 setState 只是将用户设置为数据,但数据没有“信息”字段。基本上,您正在设置 this.users,然后读取 this.info.users。

标签: javascript json reactjs rest


【解决方案1】:

我认为您需要从状态打印信息,而不是属性本身。在返回的渲染 HTML 中也会发生同样的情况。此外,setState 应该修改info 属性,而不是其中的users 属性。您可以在下面找到应用了更改的代码:

class App extends React.Component {
  componentDidMount() {
    const url = "api/testQuery.php";
    axios
      .get(url)
      .then((response) => data)
      .then((data) => {
        this.setState({ info: { users: data } });
        console.log(this.state.info.users);
      });
  }
  info = {
    users: [],
  };
  render() {
    return (
      <React.Fragment>
        <h1>All Users</h1>
        <table border="1" width="100%">
          <tr>
            <th>Username</th>
            <th>Fullname</th>
            <th>Email</th>
          </tr>

          {this.state.info.users.map((user) => (
            <tr>
              <td>{user.username}</td>
              <td>{user.fullname}</td>
              <td>{user.email}</td>
            </tr>
          ))}
        </table>
      </React.Fragment>
    );
  }
}

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

【讨论】:

  • “信息”这个词是个问题。用“状态”替换“信息”修复了它。非常感谢您的帮助。
猜你喜欢
  • 2019-04-01
  • 2017-10-25
  • 2011-12-04
  • 2013-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2017-12-02
相关资源
最近更新 更多