【问题标题】:Getting the sum of select values to render on screen in react在反应中获取选择值的总和以在屏幕上呈现
【发布时间】:2020-09-10 08:49:14
【问题描述】:

我正在构建一个应用程序,它呈现 9 个框,每个框具有 4 个不同的选择值。 select 的选项有:关闭成功、关闭不成功、回调和打开。我正在尝试找到一种方法来计算所有成功关闭和所有未成功关闭并将数字呈现在屏幕顶部。 解决这个问题的最佳方法是什么?如果有人能指出我正确的方向,我将不胜感激。非常感谢。

父组件BackGround.js(调用API,设置状态,然后映射渲染9个卡片组件。):

import React, { Component } from "react";
import axios from "axios";
import Card from "./Card";

export default class Background extends Component {
  constructor(props) {
    super(props);

    this.state = {
      people: [],
    };
    this.handleRerender = this.handleRerender.bind(this);
  }

  async handleRerender() {
    let data = await axios
      .get(`https://randomuser.me/api/?results=9`)
      .catch((error) => {
        alert("Error ========> Fetching Failed Please reload page", error);
        this.handleRerender();
      });

    this.setState({
      people: data.data.results,
    });
  }

  async componentDidMount() {
    let data = await axios
      .get(`https://randomuser.me/api/?results=9`)
      .catch((error) => {
        alert("Error ========> Fetching Failed", error);
        this.handleRerender();
      });

    this.setState({
      people: data.data.results,
    });
  }

  render() {
    const people = this.state.people.map((person) => {
      return (
        <Card
          key={person.cell}
          name={`${person.name.first}  ${person.name.last}`}
          email={person.email}
          phone={person.phone}
          company={person.location.city}
        />
      );
    });

    return (
      <>
        <div className='top'>
          <h1 className="title">XpressLeads</h1>
          <div className="btn">
            <button onClick={this.handleRerender}>Get new leads</button>
          </div>
        </div>
        <div className="container">{people}</div>
      </>
    );
  }
}

子组件 Card.js(渲染选择框和其他一些道具)

import React from "react";
import { CopyToClipboard } from "react-copy-to-clipboard";

class Card extends React.Component {
  state = {
    isEmailed: false,
    isCalled: false,
    copied: false,
    selectValue: "",
  };

  handleIsEmailedChange = () => {
    this.setState({
      isEmailed: !this.state.isEmailed,
    });
  };

  handleIsCalledChange = () => {
    this.setState({
      isCalled: !this.state.isCalled,
    });
  };

  handleCopy = () => {
    this.setState({
      copied: !this.state.copied,
    });
    setTimeout(() => {
      this.setState({ copied: false });
    }, 1000);
  };

  handleDropdownChange = (e) => {
    this.setState({ selectValue: e.target.value });
  };

  handleCount = () => {
    const success = this.state.selectValue === "success";
    const fail = this.state.selectValue === "fail";
    const callback = this.state.selectValue === "callback";

    if (success) {
      return <p>success</p>;
    }
    if (fail) {
      return <p>fail</p>;
    }
    if (callback) {
      return <p>callback</p>;
    }
  };

  render() {
    const success = this.state.selectValue === "success";
    const fail = this.state.selectValue === "fail";
    const callback = this.state.selectValue === "callback";

    console.log(this.state.totalSuccess);
    return (
      <div
        className={
          success
            ? "box success"
            : fail
            ? "box fail"
            : callback
            ? "box callback"
            : "box"
        }
      >
        <div className="outcome">
          <ion-icon name="podium-outline"></ion-icon>
          <label htmlFor="outcome">Outcome {"  "}</label>
          <select name="outcome" onChange={this.handleDropdownChange}>
            <option value="open">open</option>
            <option value="success">close successful</option>
            <option value="fail">close unsuccessful</option>
            <option value="callback">callback </option>
          </select>
        </div>

        {this.handleCount()}

        <h4>
          <ion-icon name="people-circle-outline"></ion-icon>Name:{" "}
          {this.props.name}
        </h4>
        <h4>
          <ion-icon name="business-outline"></ion-icon>
          Company: {this.props.company}
        </h4>
        <h4>
          <ion-icon name="mail-outline"></ion-icon>
          Email: {"  "}
          <a className="link" href={`mailto:${this.props.email}`}>
            {this.props.email}
          </a>
          <input
            type="checkbox"
            checked={this.state.isEmailed}
            onChange={this.handleIsEmailedChange}
          />
          emailed
        </h4>

        <h4 className="number">
          <ion-icon name="call-outline"></ion-icon>Number: {this.props.phone}
          <input
            type="checkbox"
            checked={this.state.isCalled}
            onChange={this.handleIsCalledChange}
          />
          called
          <CopyToClipboard text={this.props.phone}>
            <button className="copy-btn" onClick={this.handleCopy}>
              {this.state.copied ? "copied" : "copy"}
            </button>
          </CopyToClipboard>
        </h4>
      </div>
    );
  }
}

export default Card;

【问题讨论】:

  • 从您提供的代码中您想要什么并不完全清楚。还有一堆与&lt;select&gt; 无关的其他代码可以通过删除来使人们更容易阅读/理解您想要解决的特定问题。可能设置 9 个&lt;select&gt;'s 并将它们存储在 state 中将是一个好的开始(在代码盒中更容易:))
  • 你说得对,我很抱歉。我添加了完整的代码和简短的解释。希望有帮助

标签: javascript reactjs


【解决方案1】:

您是否尝试在 handleDropdownChange 方法中进行计数?也许是这样的

handleDropdownChange = (e) => {
  let { successCount, unsuccessCount } = this.state;
  switch(e.target.value) {
    case 'success':
      successCount += 1;
      break;
    case 'fail':
      unsuccessCount += 1;
      break;
    default:
      break;
  }

  this.setState({
    successCount: successCount,
    unsuccessCount: unsuccessCount,
    selectValue: e.target.value
  });
};

使用successCount,应该声明unsuccessCount

【讨论】:

  • 我喜欢这个主意。我已经尝试过您的代码,当我选择成功选项时,它确实将 1 添加到状态但保持在 1。当我选择其他框时,由于某种原因它总是保持在 1。我不会添加其他值
  • setState 确实提供了显示先前状态以进行更改的参数。每次设置状态时,您都应该使用它来增加计数值。结帐this document
猜你喜欢
  • 1970-01-01
  • 2021-08-09
  • 2022-11-16
  • 2021-12-18
  • 2019-11-03
  • 2018-04-05
  • 1970-01-01
  • 2020-06-09
  • 2022-08-10
相关资源
最近更新 更多