简体   繁体   English

React js 中的 State 嵌套 Object 的变化值 - Z46F3EA056CAA3126B91F3F70BEDFEA068CZ Z86408593C34AF726FDD90B工作

[英]Change Value of State Nested Object in React js - Map Function isnt working

Fairly new with React and wanting to build a simple front end application (no database) with React. React 相当新,想用 React 构建一个简单的前端应用程序(无数据库)。

The app is a trivia game and it involves creating "users" which involves a id #, name, a "answers" field to keep track of the answers they've provided and "points" which is an integer of 0 until the player answers a question correctly.该应用程序是一个琐事游戏,它涉及创建“用户”,其中涉及 id #、名称、“答案”字段以跟踪他们提供的答案和“分数”,即 integer 为 0,直到玩家回答一个正确的问题。

THE PROBLEM is creating a function to add +1 to the users 'answers'.问题是创建 function 为用户的“答案”添加 +1。 Right now when I complete the function, it saves the state as a object and therefore gives my map() function errors.现在,当我完成 function 时,它将 state 保存为 object,因此给出了我的 map() ZC1C4125264C183 错误。

My code:我的代码:

import { Button } from "bootstrap";
import React, { Component, useState } from "react";
import { Header, Table } from "semantic-ui-react";
import NewPlayer from "./NewPlayer";
import DeletePlayer from "./DeletePlayer";

// STATE
class Trivia extends Component {
  constructor(props) {
    super(props);
    this.state = {
      players: [{ name: "PLAYER", id: 0, answers: 0, points: 0 }], // Need to change this
    };
    this.deletePlayer = this.deletePlayer.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.addPlayer = this.addPlayer.bind(this);
    this.answerYes = this.answerYes.bind(this);
  }

  // What I want it to do: onClick, add +1 to answers (eventually, add +1 to points)

  deletePlayer = (e, nid) => {
    e.preventDefault();
    var players = this.state.players;

    for (var i = 0; i < players.length; i++)
      if (players[i].id && players[i].id === nid) {
        players.splice(i, 1);
        break;
      }

    this.setState({ players: players });
  };

  addPlayer = (e) => {
    e.preventDefault();
    if (!this.state.newPlayerName) {
      return;
    }
    var currentPlayers = this.state.players;
    const lastID = currentPlayers[currentPlayers.length - 1];
    var variable = lastID.id + 1;
    const newPlayer = {
      name: this.state.newPlayerName,
      id: variable,
      answers: 0,
      points: 0,
    };
    this.setState({ players: [...this.state.players, newPlayer] });
    document.getElementById("name").value = "";
  };

  // FUNCTION THAT NEEDS HELP !!!
  answerYes = (e, id) => {
    // On click, answer goes up +1
    e.preventDefault();
    var players = this.state.players;
    this.setState({ players: this.state.players[id].answers + 1 });
  };

  answerNo = (e, id) => {
    e.preventDefault();
    // Subtract point away
  };
  handleChange(e) {
    this.setState({ newPlayerName: e.target.value });
  }

  render() {
    var { players } = this.state;
    console.log(players);

    return (
      <div>
        <Header as="h1">Players</Header>
        <Table>
          <thead>
            <tr>
              <th>Player #</th>
              <th>Name</th>
              <th>Answers</th>
              <th>Points</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {players.map((player) => {
              return (
                <tr>
                  <td>{player.id}</td>
                  <td>{player.name}</td>
                  <td>
                    {player.answers}
                    <button
                      onClick={(e) => {
                        this.answerYes(e, player.id);
                      }}
                    >
                      Correct
                    </button>
                    <button
                      onClick={(e) => {
                        this.answerNo(e, player.id);
                      }}
                    >
                      Incorrect
                    </button>{" "}
                  </td>
                  <td>{player.points}</td>
                  <td>
                    <button
                      onClick={(e) => {
                        this.deletePlayer(e, player.id);
                      }}
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </Table>
        <div>
          <form onSubmit={this.addPlayer}>
            <input
              type="text"
              value={this.state.name}
              id="name"
              placeholder="add 
                           player name...."
              onChange={this.handleChange}
            />

            <input type="submit" value="add player" />
          </form>
        </div>
      </div>
    );
  }
}

export default Trivia;

Right now the error I am getting is: Uncaught TypeError: players.map is not a function.现在我得到的错误是:Uncaught TypeError: player.map is not a function。 I need help saving the state object.我需要帮助保存 state object。 Thank you谢谢

The problem is that you are trying to map var players which does not exist before clicking button问题是您正在尝试单击按钮之前不存在的 map var players

<button
  onClick={(e) => {
  this.answerYes(e, player.id);
  }}>

You should change the logic with your requirement flow or alternatively you can assign var player at first render in useEffect then can change in function您应该根据您的需求流程更改逻辑,或者您可以在第一次渲染时在useEffect中分配 var player,然后可以在 function 中更改

useEffect(() => {

var player = this.state.players
}, [] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM