簡體   English   中英

React 循環遍歷數組並渲染

[英]React Loop through array and render

我正在嘗試顯示這兩個 arrays。 每次單擊該按鈕時,都會生成一個新用戶並將其添加到數組中。 我想讓它渲染整個數組,而不僅僅是最新的行。 我已經嘗試了很多東西。 我一直在網上看到有關映射的信息,但我無法讓其中任何一個正常工作。

 import React from "react"; import ReactDOM from "react-dom"; import $ from "jquery"; var personlist = []; var imglist = []; var i = 0; class People extends React.Component { constructor(props) { super(props); this.state = { name: "firstlastname", image: "image" }; } static getDerivedStateFromProps(props, state) { getUser = () => { var usersname; var thumbnail; $.ajax({ url: "https://randomuser.me/api/?inc=name,picture", data: "json", async: false, success: function (data) { usersname = JSON.stringify( data.results[0].name.first + " " + data.results[0].name.last ); thumbnail = JSON.stringify(data.results[0].picture.thumbnail); newUser = usersname; newImage = thumbnail; var eventstring = new String(); //remove quotes from image string eventstring = newImage.toString().replace(/"/g, ""); //remove quotes from image string personlist.push([newUser, eventstring]); imglist.push([eventstring]); console.log(personlist); }, error: function (errormsg) { console.log(errormsg); } }); }; this.getUser(); var eventstring = new String(); //remove quotes from image string eventstring = newImage.toString().replace(/"/g, ""); //remove quotes from image string return { name: newUser, image: eventstring }; } changeColor = () => { //change state to rerender this.setState({ name: "updt" }); i++; return { name: "updt" }; }; render() { return ( <div> <button onClick={this.changeColor}>Generate New Person</button> <div> <h1>{personlist[i][0]}</h1> <img src={personlist[i][1]} alt="none" /> </div> </div> ); } } export default People;

React components can store data in their state variable and in classes, you can access the state using this.state and if you want to modify the state, you can use this.setState . 您可以在反應站點上閱讀更多內容。

下面是您提供的重構代碼,我在 state 中初始化了people數組。 而在fetchPerson方法中,你可以看到獲取數據后,它會調用this.setState方法來更新當前的 state,這會導致組件重新渲染。 我已將onGetNewPerson changeColor ,用於渲染組件以獲取新人。 In the render method, you can see I am using the map function which is available to arrays, you can read more about this in the Mozilla Javascript documentation. 如果您不了解類,可以查看功能組件。

class People extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "firstlastname",
      image: "image",
      people: [],
    };

    this.onGetNewPerson = this.onGetNewPerson.bind(this);
  }

  componentDidMount() {
    this.fetchPerson();
  }

  fetchPerson() {
    $.ajax({
      url: "https://randomuser.me/api/?inc=name,picture",
      data: "json",
      async: false,
      success: function (data) {
        // if you want to replace the people array in the state
        // this.setState({ people: data.results });

        // if you want to append to the people array
        this.setState((prevState) => {
          return {
            people: prevState.people.concat(data.results)
          };
        });
      }
    });
  }

  parsePerson(person) {
    const name = JSON.stringify(
      person.name.first + " " + person.name.last
    );
    const image = JSON.stringify(person.picture.thumbnail).toString().replace(/"/g, "");

    return { name, image };
  }

  onGetNewPerson = () => {
    // on click => fetch and append new person
    this.fetchPerson();
  };

  render() {
    return (
      <div>
        <button onClick={this.onGetNewPerson}>Generate New Person</button>

        <div>
          {this.state.people.map((person, i) => {
            const p = this.parsePerson(person);
            return (
              <div key={"person-" + i}>
                <h1>{p.name}</h1>
                <img src={p.image} alt="none" />
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

暫無
暫無

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

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