【问题标题】:How to develop previous and next buttons in React?如何在 React 中开发上一个和下一个按钮?
【发布时间】:2020-07-27 04:06:16
【问题描述】:

我是 React 新手,我很难想出代码来让我的按钮执行我想要的操作。我希望他们循环遍历给定的数组并每次显示不同的信息。我尝试了 for loop 和 forEach 方法,并尝试将项目添加到自身,但似乎没有任何效果。我试图阅读有关 React 的文档,但它什么也没给我。我不知道在 React 中是否有特定的方法可以做到这一点,有人可以指出正确的方向吗?

这是我的代码:

class Members extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userInput: null,
      senators: [],
      represenatives: [],
      bills: [],
      
    }
  }

  handleChange = (e) => {
    this.setState({
      userInput: e.target.value.toUpperCase()
    })
  }

  right = (i) => {
    i.forEach(element => {
      element = element++
      console.log(element)
    });

  }
  left = (i) => {

    console.log(i.id)
  }

  componentDidMount() {
    const key = `xCaHBd8gI5ZJSOUXWFJGOXZBjJtMbvoIcip0kSmS`
    const urls = [`https://api.propublica.org/congress/v1/116/senate/members.json`,
      `https://api.propublica.org/congress/v1/102/house/members.json`,
      `https://api.propublica.org/congress/v1/statements/latest.json`,
      `https://api.propublica.org/congress/v1/bills/search.json`];

    let requests = urls.map(url => fetch(url, {
      type: "GET",
      dataType: 'json',
      headers: {
        'X-API-Key': key
      }
    }))
    Promise.all(requests)
      .then(res => {
        return Promise.all(res.map(res => res.json()));
      }).then(response => {
        this.setState({
          senators: response[0].results[0].members,
          represenatives: response[1].results[0].members,
          bills: response[2].results
        })
      }).catch(err => {
        console.log(err)
      })

  }

  render() {

    const { senators, bills, represenatives, userInput } = this.state;


    const inSenate = senators.filter(
      (senator) => senator.state === userInput
    )

    const inHouse = represenatives.filter(
      (represenative) => represenative.state === userInput
    )

    const draft = bills.find(
      (bill) => bill.name === inSenate.last_name)



    return (

      <div className="congress">
        <div className="users">
          <h2>{this.state.userInput}</h2>
          <input className="userInput" onChange={this.handleChange} />
        </div>

        {inSenate.map((senate, i) => {
          return (
            <div key={senate.id} className="senate">
              <h2 className="senateName">Senate</h2>
              <ul className="bio">
                <h2 >{senate.short_title + " " + senate.first_name + " " + senate.last_name}</h2>
                <li>{senate.title}</li>
                <li>State: <strong>{senate.state}</strong></li>
                <li>Party: <strong>{senate.party}</strong></li>
                <li>DOB: <strong>{senate.date_of_birth}</strong></li>
                <li>Next Election: <strong>{senate.next_election}</strong></li>
                <li>Missed Votes: <strong>{senate.missed_votes}</strong></li>
                <li> Votes With Party Percentage: <strong>{senate.votes_with_party_pct + "%"}</strong></li>
                <li>Votes Against Party Percentage: <strong>{senate.votes_against_party_pct + "%"}</strong></li>
              </ul>
            </div>
          )
        })}

        {inHouse.map((rep, i) => {
          return (
            <div key={rep.id} className="house">
              <h2 className="numbers" >Your state has {inHouse.length} Represenative(s)</h2>
              <h2 >{rep.short_title + " " + rep.first_name + " " + rep.last_name}</h2>
              <ul className="bio">
                <li  >{rep.title}</li>
                <li  >State: <strong>{rep.state}</strong></li>
                <li  >Party: <strong>{rep.party}</strong></li>
                <li  >DOB: <strong>{rep.date_of_birth}</strong></li>
                <li  >Next Election: <strong>{rep.next_election}</strong></li>
                <li  >Missed Votes: <strong>{rep.missed_votes}</strong></li>
                <li  > Votes With Party Percentage: <strong>{rep.votes_with_party_pct + "%"}</strong></li>
                <li  >Votes Against Party Percentage: <strong>{rep.votes_against_party_pct + "%"}</strong></li>
              </ul>
              <button onClick={() => this.left(inHouse)} className="left btn"></button>
              <button onClick={() => this.right(inHouse)} className="right btn"></button>
            </div>
          )
        })}
      </div>

    )
  }
}

【问题讨论】:

  • 请提供更多细节。你到底想发生什么。内部地图在渲染时显示所有代表。

标签: javascript reactjs button


【解决方案1】:

这里有一个解决方案。每次按下按钮时,它都会使用状态来更改信息:

import React, { useEffect, useState, Component } from "react";
import { InputText } from "primereact/inputtext";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userInput: "CA",
      senators: [],
      represenatives: [],
      bills: [],
      repst: 0, //state for changing representative everytime the button is pressed
    };
  }

  handleChange = (e) => {
    this.setState({
      userInput: e.target.value.toUpperCase(),
    });
  };

  right = (i) => {
    if (this.state.repst + 1 < i.length)
      this.setState({
        repst: this.state.repst + 1,
      });
  };
  left = (i) => {
    if (this.state.repst - 1 > -1)
      this.setState({
        repst: this.state.repst - 1,
      });
  };

  componentDidMount() {
    const key = `xCaHBd8gI5ZJSOUXWFJGOXZBjJtMbvoIcip0kSmS`;
    const urls = [
      `https://api.propublica.org/congress/v1/116/senate/members.json`,
      `https://api.propublica.org/congress/v1/102/house/members.json`,
      `https://api.propublica.org/congress/v1/statements/latest.json`,
      `https://api.propublica.org/congress/v1/bills/search.json`,
    ];

    let requests = urls.map((url) =>
      fetch(url, {
        type: "GET",
        dataType: "json",
        headers: {
          "X-API-Key": key,
        },
      })
    );
    Promise.all(requests)
      .then((res) => {
        return Promise.all(res.map((res) => res.json()));
      })
      .then((response) => {
        this.setState({
          senators: response[0].results[0].members,
          represenatives: response[1].results[0].members,
          bills: response[2].results,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    const { senators, bills, represenatives, userInput } = this.state;

    const inSenate = senators.filter((senator) => senator.state === userInput);

    const inHouse = represenatives.filter(
      (represenative) => represenative.state === userInput
    );

    const draft = bills.find((bill) => bill.name === inSenate.last_name);

    return (
      <div className="congress">
        <div className="users">
          <h2>{this.state.userInput}</h2>
          <input className="userInput" onChange={this.handleChange} />
        </div>
        {inSenate.map((senate, i) => {
          return (
            <div key={senate.id} className="senate">
              <h2 className="senateName">Senate</h2>
              <ul className="bio">
                <h2>
                  {senate.short_title +
                    " " +
                    senate.first_name +
                    " " +
                    senate.last_name}
                </h2>
                <li>{senate.title}</li>
                <li>
                  State: <strong>{senate.state}</strong>
                </li>
                <li>
                  Party: <strong>{senate.party}</strong>
                </li>
                <li>
                  DOB: <strong>{senate.date_of_birth}</strong>
                </li>
                <li>
                  Next Election: <strong>{senate.next_election}</strong>
                </li>
                <li>
                  Missed Votes: <strong>{senate.missed_votes}</strong>
                </li>
                <li>
                  {" "}
                  Votes With Party Percentage:{" "}
                  <strong>{senate.votes_with_party_pct + "%"}</strong>
                </li>
                <li>
                  Votes Against Party Percentage:{" "}
                  <strong>{senate.votes_against_party_pct + "%"}</strong>
                </li>
              </ul>
            </div>
          );
        })}
        {inHouse[this.state.repst] ? (
          <div key={inHouse[this.state.repst].id} className="house">
            {console.log(inHouse)}
            <h2 className="numbers">
              Your state has {inHouse.length} Represenative(s)
            </h2>
            <h2>
              {inHouse[this.state.repst].short_title +
                " " +
                inHouse[this.state.repst].first_name +
                " " +
                inHouse[this.state.repst].last_name}
            </h2>
            <ul className="bio">
              <li>{inHouse[this.state.repst].title}</li>
              <li>
                State: <strong>{inHouse[this.state.repst].state}</strong>
              </li>
              <li>
                Party: <strong>{inHouse[this.state.repst].party}</strong>
              </li>
              <li>
                DOB: <strong>{inHouse[this.state.repst].date_of_birth}</strong>
              </li>
              <li>
                Next Election:{" "}
                <strong>{inHouse[this.state.repst].next_election}</strong>
              </li>
              <li>
                Missed Votes:{" "}
                <strong>{inHouse[this.state.repst].missed_votes}</strong>
              </li>
              <li>
                {" "}
                Votes With Party Percentage:{" "}
                <strong>
                  {inHouse[this.state.repst].votes_with_party_pct + "%"}
                </strong>
              </li>
              <li>
                Votes Against Party Percentage:{" "}
                <strong>
                  {inHouse[this.state.repst].votes_against_party_pct + "%"}
                </strong>
              </li>
            </ul>
            <button onClick={() => this.left(inHouse)} className="left btn">
              Next
            </button>
            <button onClick={() => this.right(inHouse)} className="right btn">
              Prev
            </button>
          </div>
        ) : (
          ""
        )}
      </div>
    );
  }
}

【讨论】:

  • 非常感谢您的解决方案。当我将它单独放在元素上时,它最有效,但当我把它放在键上时它不起作用。它说它们必须是独一无二的。我知道你可能在睡觉,但是当你找到时间时,你能不能引导我完成你的思考过程。我想知道你是怎么想出这个逻辑的,因为我有时会遇到麻烦。
  • 我必须查看您的代码才能对此发表评论。但简单地说,repst 是一种状态。状态的特殊属性之一是它在运行时更新值。所以我们可以对其进行更改,它们将立即反映在渲染中。使用 const、var、let 等你不能这样做。这就是我的代码背后的逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多