Reactjs:如何在 reactjs 中更新投票计数

IT技术 javascript reactjs
2021-05-15 11:04:42

下面的代码旨在更新投票系统。通过在页面加载时显示结果,它可以正常工作。

这是我的问题:我需要在单击获取投票计数”按钮时更新每个用户的投票

在后端,我有 php 代码,它返回数组数据,如下所示。

有人可以帮助我显示数组值并根据用户的投票方式更新例如(投票给 11)吗?

<?php
// Update user response on a post

    $return_arr[]= array("vote"=>"11");

    echo json_encode($return_arr);
    exit;

?>

这里是 axios API 调用返回的数组

[{"vote":"11"}]

这是代码

import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import axios from 'axios';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: false
    };
  }

  componentDidMount() {
    this.setState({
      data: [
        { id: "1", name: "Tony", vote: "3" },
        { id: "2", name: "Mark", vote: "6" },
        { id: "3", name: "Joy", vote: "2" }
      ]
    });
  }

  handleVote(person_id, person_vote) {
    const data_vote = {
      person_id: person_id,
      person_vote: person_vote
    };
    axios
      .get("http://localhost/vote.php", { data_vote })
      .then(response => {
        this.setState({ result_vote: response.data });
        console.log(this.state.result_vote);
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <span>
        <label>
          <ul>
            {this.state.data.map((person, i) => (
              <li key={i}>
                {person.name} --(vote count: {person.vote})
                <br />
                <input
                  type="button"
                  value="Get Vote Counts"
                  onClick={() => this.handleVote(person.id, person.vote)}
                />
              </li>
            ))}
          </ul>
        </label>
      </span>
    );
  }
}
2个回答

您应该datavote从 fetch 响应中获取数据设置您的状态你有person_id你的处理程序并获得一个包含vote的数组因此,map通过您的data状态找到相关person并更新其vote值。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: false
    };
  }

  componentDidMount() {
    this.setState({
      data: [
        { id: "1", name: "Tony", vote: "3" },
        { id: "2", name: "Mark", vote: "6" },
        { id: "3", name: "Joy", vote: "2" }
      ]
    });
  }

  handleVote(person_id, person_vote) {
    const data_vote = {
      person_id: person_id,
      person_vote: person_vote
    };
    axios
      .get("http://localhost/vote.php", { data_vote })
      .then(response => {
        const newData = this.state.data.map(person => {
          if (person.id !== person_id) return person;
          return { ...person, vote: response.data[0].vote };
        });
        this.setState(state => ({
          data: newData
        }));
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <span>
        <label>
          <ul>
            {this.state.data.map(person => (
              <li key={person.id}>
                {person.name} --(vote count: {person.vote})
                <br />
                <input
                  type="button"
                  value="Get Vote Counts"
                  onClick={() => this.handleVote(person.id, person.vote)}
                />
              </li>
            ))}
          </ul>
        </label>
      </span>
    );
  }
}

尽量避免使用索引作为键。你有一个person.id所以在你的map方法中使用它此外,作为增强功能,您可以重构代码并创建Person组件。您可以传递相关数据和投票处理程序,然后在那里设置更新逻辑。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: false,
    };
  }

  componentDidMount() {
    this.setState({
      data: [
        { id: "1", name: "Tony", vote: "3" },
        { id: "2", name: "Mark", vote: "6" },
        { id: "3", name: "Joy", vote: "2" },
      ],
    });
  }

  handleVote = (person) => {
    const data_vote = {
      person_id: person.id,
      person_vote: person.vote,
    };
    axios
      .get("http://localhost/vote.php", { data_vote })
      .then((response) => {
        const newData = this.state.data.map((el) => {
          if (el.id !== person.id) return el;
          return { ...el, vote: response.data[0].vote };
        });
        this.setState({ data: newData });
      })
      .catch((error) => {
        console.log(error);
      });
  };

  render() {
    return (
      <span>
        <label>
          <ul>
            {this.state.data.map(person => (
              <Person
                key={person.id}
                person={person}
                handleVote={this.handleVote}
              />
            ))}
          </ul>
        </label>
      </span>
    );
  }
}

const Person = (props) => {
  const { person, handleVote } = props;
  const onVote = () => handleVote(person);
  return (
    <li>
      {person.name} --(vote count: {person.vote})
      <br />
      <input type="button" value="Get Vote Counts" onClick={onVote} />
    </li>
  );
};

因此,由于您的处理程序函数正在获取person_id并且您的调用正在返回新的投票计数,您应该在状态中更新数据表中的当前人员对象。

下面是一个例子:

更新当前用户的投票数