反应,打印数组状态并在按下按钮时更新状态

时间:2018-11-29 20:25:42

标签: javascript reactjs

当按下其中一个按钮时,我需要打印日志阵列。当按下其中一个按钮而不进行多次打印时,如何在React中更新状态并将其打印到屏幕上?

这应该像控制台一样用作数据记录,但需要在页面上呈现。

到目前为止,所有其他功能均正常运行,并且按钮调用了将生成结果推送到日志数组的函数。

const desert = [
  { content: "Goblin, Cave Bat, Goblin" },
  { content: "Ahriman" },
  { content: "Desertpede, Desert Sahagin" },
  { content: "Antlion, Antlion, Antlion" },
  { content: "No Encounter" },
  { content: "No Encounter" },
  { content: "No Encounter" }
];

const forest = [
  { content: "Hindlegs, Axebeak, Hindlegs" },
  { content: "Arachne" },
  { content: "Bood Eye, Flan" },
  { content: "Bomb, Bomb, Bomb" },
  { content: "No Encounter" },
  { content: "No Encounter" },
  { content: "No Encounter" }
];

const goblin = [
  { content: "ATK 1" },
  { content: "ATK 2" },
  { content: "ATK 3" },
  { content: "ATK 4" },
  { content: "ATK 5" },
  { content: "ATK 6" },
  { content: "Miss" }
];

const arachne = [
  { content: "ATK 1" },
  { content: "ATK 2" },
  { content: "ATK 3" },
  { content: "ATK 4" },
  { content: "ATK 5" },
  { content: "ATK 6" },
  { content: "Miss" }
];

const log = [];

class DesertGenerator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      content: ""
    };

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

  desertGeneration() {
    let number = Math.floor(Math.random() * desert.length);

    let generation = desert[number].content;

    this.setState({ content: generation });

    log.push(generation);
    console.log(log);
  }

  render() {
    return (
      <DesertButton
        handleDesertGeneration={this.desertGeneration}
        generation={this.state.content}
      />
    );
  }
}

class ForestGenerator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      content: ""
    };

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

  forestGeneration() {
    let number = Math.floor(Math.random() * forest.length);

    let generation = forest[number].content;

    this.setState({ content: generation });

    log.push(generation);
    console.log(log);
  }
  render() {
    return (
      <ForestButton
        handleForestGeneration={this.forestGeneration}
        generation={this.state.content}
      />
    );
  }
}

class GoblinGenerator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      content: ""
    };

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

  goblinGeneration() {
    let number = Math.floor(Math.random() * goblin.length);

    let generation = goblin[number].content;

    this.setState({ content: generation });

    log.push(generation);
    console.log(log);
  }

  render() {
    return (
      <GoblinButton
        handleGoblinGeneration={this.goblinGeneration}
        generation={this.state.content}
      />
    );
  }
}

class ArachneGenerator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      content: ""
    };

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

  arachneGeneration() {
    let number = Math.floor(Math.random() * arachne.length);

    let generation = arachne[number].content;

    this.setState({ content: generation });

    log.push(generation);
    console.log(log);
  }
  render() {
    return (
      <ArachneButton
        handleArachneGeneration={this.arachneGeneration}
        generation={this.state.content}
      />
    );
  }
}

class DesertButton extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <button
        type="button"
        id="Desert"
        className="btn"
        onClick={this.props.handleDesertGeneration}
      >
        Desert
      </button>
    );
  }
}

class ForestButton extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <button
        type="button"
        id="Forest"
        className="btn"
        onClick={this.props.handleForestGeneration}
      >
        Forest
      </button>
    );
  }
}

class GoblinButton extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <button
        type="button"
        id="Goblin"
        className="btn"
        onClick={this.props.handleGoblinGeneration}
      >
        Goblin
      </button>
    );
  }
}

class ArachneButton extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <button
        type="button"
        id="Arachne"
        className="btn"
        onClick={this.props.handleArachneGeneration}
      >
        Arachne
      </button>
    );
  }
}

ReactDOM.render(
  <div>
    <DesertGenerator />
    <ForestGenerator />
    <GoblinGenerator />
    <ArachneGenerator />
  </div>,
  document.getElementById("content")
);

1 个答案:

答案 0 :(得分:0)

我不确定您要什么,但我相信这可以满足您的要求。

我减少了很多组件,因为它们是重复的。我还使用PropTypes来确保Finished input (async). Time: 43.90000000000873 Arguments(3) 0: data: Array(1136) [0 … 99] 0: (9) [ "CONTENT TYPE", "TITLE", "ABBR", "ISSN", "e-ISSN", "PUBLICATION RANGE: START", "PUBLICATION RANGE: LATEST PUBLISHED", "SHORTCUT URL", "ARCHIVE URL" ] 1: (9) [ "Journals", "ACM Computing Surveys ", "ACM Comput. Surv.", "0360-0300", "1557-7341", "Volume 1 Issue 1 (March 1969)", "Volume 46 Issue 1 (October 2013)", "http://dl.acm.org/citation.cfm?id=J204", "http://dl.acm.org/citation.cfm?id=J204&picked=prox" ] / state声明和用法的一致性(基本上,您不能从prop向下传递string并尝试就像在parent中一样在child中调用它-字符串保留为字符串,函数保留为函数,...等等-不管它们传递了多少次。)

工作示例:https://codesandbox.io/s/qvyw4yv36

components / Content.js

function

components / App.js

export const content = {
  desert: [
    "Goblin, Cave Bat, Goblin",
    "Ahriman",
    "Desertpede, Desert Sahagin",
    "Antlion, Antlion, Antlion",
    "No Encounter",
    "No Encounter",
    "No Encounter"
  ],
  forest: [
    "Hindlegs, Axebeak, Hindlegs",
    "Arachne",
    "Bood Eye, Flan",
    "Bomb, Bomb, Bomb",
    "No Encounter",
    "No Encounter",
    "No Encounter"
  ],
  goblin: ["ATK 1", "ATK 2", "ATK 3", "ATK 4", "ATK 5", "ATK 6", "Miss"],
  arachne: ["ATK 1", "ATK 2", "ATK 3", "ATK 4", "ATK 5", "ATK 6", "Miss"]
};

export const contentTypes = ["desert", "forest", "goblin", "arachne"];

export const logTypes = [
  { title: "Generation Log", type: "generation" },
  { title: "Actions Log", type: "actions" },
  { title: "Actions Log (by type)", type: "actionsByType" }
];

components / Generator.js

import React, { Component } from "react";
import Generator from "./Generator";
import Logger from "./Logger";
import { content, contentTypes, logTypes } from "./Content";

export default class App extends Component {
  state = {
    generation: {},
    actions: [],
    actionsByType: [],
    count: 0
  };

  logGeneration = (id, generation) =>
    this.setState(prevState => {
      const newCount = prevState.count + 1; // count of action (1, 2, ...etc)
      const nextAction = `action${newCount}`; // string used for action property (action1, action2, ...etc)

      return {
        generation: { ...prevState.generation, [id]: generation }, // spread out previous generation state, add the button's [id] as a property with the selected generation
        actions: {
          ...prevState.actions, // spread out previous actions state
          [nextAction]: generation // add the [nextAction] string as a property with the selected generation
        },
         actionsByType: {
          ...prevState.actionsByType, // spread out previous actionsByType state 
          [id]: { ...prevState.actionsByType[id], [nextAction]: generation } // select id (ex: ["forest"]) and spread out previous actionsByType state, and add a [nextAction] property with the selected generation (ex: "action1": "Miss")
        },
        count: newCount
      };
    });

  render = () => (
    <div className="app">
      {contentTypes.map(type => ( // map over contentTypes 
        <Generator
          key={type} // type as key
          id={type} // type as id
          content={content[type]} // type as a content selector
          logGeneration={this.logGeneration} // pass down logGeneration method
        />
      ))}
      {logTypes.map(({ type, ...props }) => ( // map over logType, pull out type, put the rest in props
        <Logger 
          {...props} // spread and pass down props
          key={type}  // use type as key
          log={this.state[type]} // use type for selection state (ex: this.state["actions"] || this.state.actions)
        />
      ))}
    </div>
  );
}

components / Button.js

import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import Button from "../Button";

class Generator extends PureComponent {
  handleGeneration = id => {
    const number = Math.floor(Math.random() * this.props.content.length); // grab random number between 0-6 

    const generation = this.props.content[number]; // grab content by index from passed in content array (ex: forest[0-6])

    this.props.logGeneration(id, generation); // pass back id and generation to the log method
  };

  render = () => (
    <Button id={this.props.id} onHandleClick={this.handleGeneration}>
      {this.props.id}
    </Button>
  );
}

export default Generator;

Generator.propTypes = {
  logGeneration: PropTypes.func.isRequired,
  id: PropTypes.string.isRequired,
  content: PropTypes.arrayOf(PropTypes.string).isRequired
};

components / Logger.js

import React from "react";
import PropTypes from "prop-types";

const Button = ({ children, id, onHandleClick }) => (
  <div className="button-container">
    <button
      type="button"
      className="btn btn-primary"
      onClick={() => onHandleClick(id)} // pass back id on button click (ex: "forest")
    >
      {children}
    </button>
  </div>
);

export default Button;

Button.propTypes = {
  children: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  onHandleClick: PropTypes.func.isRequired
};