簡體   English   中英

使用React.js顯示列表

[英]Using React.js to show a list

我正在嘗試編寫一個非常簡單的react程序,該程序向用戶顯示一個按鈕,單擊該按鈕時,它將調用API並將結果顯示為列表。

我現在可以按一下按鈕進行調試了,我看到數據已按照我需要的方式進行拉扯和操縱,但沒有在屏幕上顯示。 這是我到目前為止所做的工作;

import React from "react";
import ReactDOM from "react-dom";

class Button extends React.Component {
  constructor(props){
  super(props);
  this.state = {
    users : []
  };
}

handleClick() {
  fetch("http://localhost:8080/api/user/")
  .then(results => {
    return results.json();
  })
  .then(data => {
    let users = data.map((user) => {
      console.log("user - ", user.name);
      return (
        <li key={user.id}>{user.name}</li>
      );
    })
    // this.setState({users: users});
    return (
      <ol>
        {users}
      </ol>
    );
  })
  .catch(function(error) {
    console.log(error);
  });
}

render(){
    return (
      <button onClick={this.handleClick}>Get All Users</button>
    );
  }
}

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

您不能像這樣異步返回jsx。 我會建議修改最后then以類似如下:

.then(data => this.setState({ data }));

您可以將默認data設置為空數組,因此您不必擔心映射。

class Button extends React.Component {
  state = { data: [] };
}

然后,更改渲染以響應state

render() {
  return (
    <ul>
      {data.map(d => <li>{d}</li>)}
    </ul>
  );
}

為了說明,這是過程:

  • onClick進行異步調用以加載數據
  • 加載數據時,它將狀態更新為新數據。
  • 更改狀態將導致調用使用新狀態進行render

這是我的建議:

import React from "react";
import ReactDOM from "react-dom";

function getData(callback) {
  fetch("http://localhost:8080/api/user/")
    .then(results => {
      return results.json();
    })
    .then(callback);
}

class Button extends React.Component {
  constructor(props) {
    super(props);

    this.handleClick = this.handleClick.bind(this);
    this.state = {
      data : null
    };
}

handleClick() {
  this.props.getData(data => this.setState({ data }));
}

_renderUsers() {
  return (
    <ol>
      { 
        this.state.data.map(user => <li key={ user.id }>{ user.name }</li>) 
      }
    </ol>
  );
}

render() {
    return (
      <div>
        <button onClick={ this.handleClick }>Get All Users</button>
        { this.state.data && this._renderUsers() }
      </div>
    );
  }
}

ReactDOM.render(<Button getData={ getData }/>, document.getElementById("root"));
  • 首先,我認為fetch應該在React組件之外。 React只是關於渲染數據而不進行ajax調用。 在上面的代碼中, getData是作為prop傳遞的外部函數。
  • 該組件不再具有異步邏輯,並且呈現狀態。 最初, data為null,后來用API中的數據填充。 setState觸發重新渲染。
  • 您的示例中的handleClick是在沒有上下文的情況下運行的,因此在內部您可能無法執行this.setState 這就是為什么在構造函數中執行this.handleClick = this.handleClick.bind(this) 我們將其綁定到組件的上下文。

您的handleClick方法只是一個事件處理程序,這意味着當您單擊按鈕時將觸發它,但實際上不呈現任何內容。 因此,在此處返回列表不會執行任何操作。

而是與用戶一起更新您的狀態,並與按鈕分開呈現它們。 例如:

import React from "react";
import ReactDOM from "react-dom";

class Button extends React.Component {
  constructor(props){
  super(props);
  this.state = {
    users : []
  };
}

handleClick() {
  fetch("http://localhost:8080/api/user/")
  .then(results => {
    return results.json();
  })
  .then(data => {
    let users = data.map((user) => {
      console.log("user - ", user.name);
      return (
        <li key={user.id}>{user.name}</li>
      );
    })
    this.setState({users: users});
  })
  .catch(function(error) {
    console.log(error);
  });
}

render(){
    return (
      <div>
        <button onClick={this.handleClick}>Get All Users</button>
        {this.state.users.length > 0 &&
          <ul>
            {this.state.users}
          </ul>
        }
      </div>
    );
  }
}

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

handleClick()方法不應返回您的結果,因為它不會對其執行任何操作,因此應更新狀態變量,該狀態變量又將更新渲染邏輯

以下有關如何更新點擊的簡短示例:

(您可以通過jsbin運行/編輯此示例: http ://jsbin.com/vumaqam/edit?html,js,output)

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {users:[]};
  }

  handleClick(){
    console.log("clikc");
    this.setState({users:["joe","smith"]});
  }


  getList(){
    // key must be unique, if user name is not unique must use other key
    return this.state.users.map((user)=>(<li key={user}>{user}</li>));
  }

  render() {
    return ( 
    <div>
      <button onClick={()=>{this.handleClick()}}>Get All Users</button>
      <ul>{this.getList()}</ul>
    </div>
    );
  }
}

React.render(
  <Button />,
  document.getElementById('react_example')
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM