如何使用Reactjs正确更新用户数量

时间:2019-02-18 22:40:07

标签: reactjs

我已经搜索了StackOverflow,但是发现的大多数解决方案目前都无法解决我的问题。

下面的代码通过reactjs显示数组中的用户记录。

现在,我有任务要显示内容显示中的用户数。

Jquery / Javascript 中,我可以使用下面的功能来实现

function updateCount(userId){
  alert('userId: ' +userId);

  var count = (userCount[userId] == undefined) ? 1 : userCount[userId] + 1;
  userCount[userId] = count;

  alert('Counter: ' +userCount[userId]);
  console.log('Counter: ' +userCount[userId]);

  $('#' + userId + ' label.userCount').html(count);
  $('#' + userId + ' label.userCount').show();

}

现在在 Reactjs 中,我创建了以下函数,在下面的函数中添加了主代码,但会引发错误

Reactjs函数

updateCount = (userId) => {
  alert('userId: ' +userId);

  var count = (userCount[userId] == undefined) ? 1 : userCount[userId] + 1;
  userCount[userId] = count;

  alert('Counter: ' +userCount[userId]);
  console.log('Counter: ' +userCount[userId]);  

  this.setState(state => ({
    data: userCount[userId]
  }));
}

这是显示的错误

bundle.js:109480 Uncaught ReferenceError: userCount is not defined
    at App._this.updateCount

以下是到目前为止的完整代码

import React, { Component, Fragment } from "react";
import { render } from "react-dom";
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            userCount: []
        };
    }

    componentDidMount() {
        var userId = "100";

        //var userCount = [];
        //this.userCount = [];

        this.setState({
            data: [
                {
                    id: "100",
                    name: "Luke"
                },
                {
                    id: "200",
                    name: "Henry"
                },
                {
                    id: "300",
                    name: "Mark"
                }
            ]
        });

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

    updateCount = userId => {
        alert("userId: " + userId);

        var count = userCount[userId] == undefined ? 1 : userCount[userId] + 1;
        userCount[userId] = count;

        alert("Counter: " + userCount[userId]);
        console.log("Counter: " + userCount[userId]);

        this.setState(state => ({
            data: userCount[userId]
        }));
    };

    render() {
        return (
            <span>
                <label>
                    <ul>
                        {this.state.data.map((person, i) => {
                            if (person.id == 100) {
                                this.updateCount(person.id);

                                return (
                                    <div key={i}>
                                        <div>
                                            {" "}
                                            {person.id}: {person.name}{" "}
                                        </div>{" "}
                                    </div>
                                );
                            } else {
                                this.updateCount(person.id);
                            }
                        })}
                    </ul>{" "}
                </label>{" "}
            </span>
        );
    }
}

更新部分 使用以下代码显示意外令牌错误

screenshot

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

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

     componentDidMount() {
   // componentWillMount(){
    var userId= '100';

    //var userCount = [];
    //this.userCount = [];


        this.setState({
          data: [
            { id: "100", name: "Luke"},
            { id: "200", name: "Henry"},
            { id: "300", name: "Mark" }
          ]
        });

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



    updateCount = (userId) => {
    //alert('userId: ' +userId);

    const {userCount} = this.state;

    var count = userCount[userId] == undefined ? 1 : userCount[userId] + 1;

      //var count = (userCount[userId] == undefined) ? 1 : userCount[userId] + 1;
      userCount[userId] = count;

    alert('Counter kk000000me: ' +userCount[userId]);
    console.log('Counter: ' +userCount[userId]);

    this.setState({data11: count});

    }

    const result = this.state.data.map((person, i) => {
        if (person.id == 100) {
            this.updateCount(person.id); //Every time this is called, it triggers setState

            return (
                <div key={i}>
                    <div>
                        {" "}
                        {person.id}: {person.name}{" "}
                    </div>{" "}
                </div>
            );
        } else {
          this.updateCount(person.id);
        }
      });


    render() {
      return (
        <span>
          <label>
            <ul> {result} </ul>
          </label>
        </span>
      );
    }

1 个答案:

答案 0 :(得分:0)

要访问状态变量,您需要这样做

this.state.userCount

在您的示例中,您尝试访问userCount而不在状态下引用它。

var count = userCount[userId] == undefined ? 1 : userCount[userId] + 1;

您应该这样做:

const {userCount} = this.state;

var count = userCount[userId] == undefined ? 1 : userCount[userId] + 1;

编辑

  

警告:无法在现有状态转换过程中(例如在渲染或其他组件的构造函数中)更新

要解决此问题,必须确保组件未在其内部触发setState。在您的代码段中,当您map遍历数据时,它将调用updateCount,然后调用this.setState(),这将触发重新渲染。

一种解决方案是将地图的结果分配给const,然后进行渲染。


  const result = this.state.data.map((person, i) => {
    if (person.id == 100) {
        this.updateCount(person.id); //Every time this is called, it triggers setState

        return (
            <div key={i}>
                <div>
                    {" "}
                    {person.id}: {person.name}{" "}
                </div>{" "}
            </div>
        );
    } else {
      this.updateCount(person.id);
    }
  });

  ...

render() {
  return (
    <span>
      <label>
        <ul> {result} </ul>
      </label>
    </span>
  );
}