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

时间:2018-12-17 06:39:16

标签: javascript reactjs

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

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

在后端,我有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 个答案:

答案 0 :(得分:0)

从获取响应中获取data数据后,应设置vote状态。您的处理程序中有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>
  );
};

答案 1 :(得分:0)

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

这里是一个例子:

Updating the vote count for the current user