Javascript React,打印数组的状态并在按下按钮时更新状态

Javascript React,打印数组的状态并在按下按钮时更新状态,javascript,reactjs,Javascript,Reactjs,我需要在按下其中一个按钮时打印日志数组。当按下其中一个按钮时,如何更新React中的状态并将其打印到屏幕上,而不进行多个打印输出 这应该是一种数据日志,很像控制台,但需要在页面上呈现 到目前为止,其他一切都正常工作,按钮调用将生成结果推送到日志数组的函数 const desert = [ { content: "Goblin, Cave Bat, Goblin" }, { content: "Ahriman" }, { content: "Desertpede, Desert Sah

我需要在按下其中一个按钮时打印日志数组。当按下其中一个按钮时,如何更新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")
);
const dest=[
{内容:“地精,洞穴蝙蝠,地精”},
{内容:“Ahriman”},
{内容:“沙漠佩德,沙漠萨哈金”},
{内容:“蚁狮,蚁狮,蚁狮”},
{内容:“无遭遇”},
{内容:“无遭遇”},
{内容:“无遭遇”}
];
常数森林=[
{内容:“后腿,斧头,后腿”},
{内容:“蜘蛛网”},
{内容:“Bood-Eye,Flan”},
{内容:“炸弹,炸弹,炸弹”},
{内容:“无遭遇”},
{内容:“无遭遇”},
{内容:“无遭遇”}
];
常量妖精=[
{内容:“ATK 1”},
{内容:“ATK 2”},
{内容:“ATK 3”},
{内容:“ATK 4”},
{内容:“ATK 5”},
{内容:“ATK 6”},
{内容:“小姐”}
];
常数arachne=[
{内容:“ATK 1”},
{内容:“ATK 2”},
{内容:“ATK 3”},
{内容:“ATK 4”},
{内容:“ATK 5”},
{内容:“ATK 6”},
{内容:“小姐”}
];
常量日志=[];
类生成器扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
内容:“”
};
this.desertGeneration=this.desertGeneration.bind(this);
}
沙漠世代(){
设number=Math.floor(Math.random()*desert.length);
让生成=沙漠[number]。内容;
this.setState({content:generation});
日志推送(生成);
console.log(log);
}
render(){
返回(
);
}
}
类ForestGenerator扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
内容:“”
};
this.forestGeneration=this.forestGeneration.bind(this);
}
森林世代(){
设number=Math.floor(Math.random()*forest.length);
let generation=林[number]。内容;
this.setState({content:generation});
日志推送(生成);
console.log(log);
}
render(){
返回(
);
}
}
类生成器扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
内容:“”
};
this.goblinggeneration=this.goblinggeneration.bind(this);
}
GoblingGeneration(){
让number=Math.floor(Math.random()*goblin.length);
让生成=妖精[number]。内容;
this.setState({content:generation});
日志推送(生成);
console.log(log);
}
render(){
返回(
);
}
}
类ArachneGenerator扩展React.Component{
建造师(道具){
超级(道具);
此.state={
内容:“”
};
this.arachenegeneration=this.arachenegeneration.bind(this);
}
蜘蛛生成(){
设number=Math.floor(Math.random()*arachne.length);
let generation=arachne[number]。内容;
this.setState({content:generation});
日志推送(生成);
console.log(log);
}
render(){
返回(
);
}
}
类扩展React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
沙漠
);
}
}
类ForestButton扩展React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
森林
);
}
}
类GoblinButton扩展了React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
妖精
);
}
}
类ArachneButton扩展了React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
蛛网膜
);
}
}
ReactDOM.render(
,
document.getElementById(“内容”)
);

我不能100%确定您的要求,但我相信这正是您想要的

我减少了很多组件,因为它们是重复的。我还用于确保
状态
/
属性
声明和使用的一致性(基本上,您不能将
字符串
父级
向下传递,并尝试在
子级
中调用它,就好像它是一个
函数一样
——字符串仍然是字符串,函数仍然是函数等等——不管它们被传递了多少次)

工作示例:

组件/Content.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" }
];
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>
  );
}
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
};
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
};
import isEmpty from "lodash/isEmpty";
import React from "react";
import PropTypes from "prop-types";

const Logger = ({ log, title }) =>
  !isEmpty(log) ? ( // if the log isn't empty...
    <div className="logger-container"> // show log
      <h1 style={{ textAlign: "center " }}>{title}</h1>
      <div className="log">
        <pre>
          <code>{JSON.stringify(log, null, 4)}</code>
        </pre>
      </div>
    </div>
  ) : null; // else show nothing

export default Logger;

Logger.propTypes = {
  log: PropTypes.oneOfType([
    PropTypes.objectOf(PropTypes.string),
    PropTypes.arrayOf(PropTypes.string),
    PropTypes.objectOf(PropTypes.objectOf(PropTypes.string))
  ]),
  title: PropTypes.string.isRequired
};
组件/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" }
];
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>
  );
}
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
};
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
};
import isEmpty from "lodash/isEmpty";
import React from "react";
import PropTypes from "prop-types";

const Logger = ({ log, title }) =>
  !isEmpty(log) ? ( // if the log isn't empty...
    <div className="logger-container"> // show log
      <h1 style={{ textAlign: "center " }}>{title}</h1>
      <div className="log">
        <pre>
          <code>{JSON.stringify(log, null, 4)}</code>
        </pre>
      </div>
    </div>
  ) : null; // else show nothing

export default Logger;

Logger.propTypes = {
  log: PropTypes.oneOfType([
    PropTypes.objectOf(PropTypes.string),
    PropTypes.arrayOf(PropTypes.string),
    PropTypes.objectOf(PropTypes.objectOf(PropTypes.string))
  ]),
  title: PropTypes.string.isRequired
};
):null;//否则什么也不显示 导出默认记录器; Logger.propTypes={ 日志:PropTypes.oneOfType([ PropTypes.objectOf(PropTypes.string), PropTypes.arrayOf(PropTypes.string), PropTypes.objectOf(PropTypes.objectOf(PropTypes.string)) ]), 标题:PropTypes.string.isRequired };
谢谢您的帮助!我一定会看的!没问题。这是一个很大的问题,所以如果你有任何问题,请随时提问。