【问题标题】:Create React States Using Classes使用类创建 React 状态
【发布时间】:2018-09-29 08:16:18
【问题描述】:

我只是从反应开始。我已经看到大多数状态都由简单的数据组成,例如对象、字符串、数字等……我希望能够使用无渲染类来保存和控制这样的状态:

import React, { Component } from 'react';
import HumanPlayer from "./players/HumanPlayer";
import Money from "./Money";
import ComputerPlayer from "./players/ComputerPlayer";
import Deck from "./cards/Deck";
import HumanBoard from "./views/PlayerBoard";
import Score from "./views/Score";
import ComputerBoard from "./views/ComputerBoard";
import Controls from "./views/Controls";

class BlackJack extends Component {

  constructor(props) {
    super(props);
    const human = new HumanPlayer({
      money: new Money({
        currency: Money.USD,
        amount: 100
      })
    });

    super(human);
    const computer = new ComputerPlayer;

    this.state = {
      human: human,
      computer: computer,
      deck: new Deck
    };
  }

  render() {
    const me = this;

    return (
        <div className="BlackJack">
          BlackJack
          <HumanBoard player={me.state.human}/>
          <Score money={me.state.human.getTotal()}/>
          <ComputerBoard player={me.state.computer}/>
          <Controls/>
        </div>
    );
  }
}

export default BlackJack;

有没有好的方法可以做到这一点,或者这更像是一种反模式?

【问题讨论】:

  • 什么是“无渲染”?你指的是容器组件吗?由类实例组成的状态的问题在于它可能无法(反)序列化。这可能会在将来导致架构问题。该问题没有解释这些类是什么以及为什么需要它们。
  • this post 可以帮到你。
  • 请问构造函数中super(human)的目的是什么?

标签: reactjs web rendering state


【解决方案1】:

我希望能够使用无渲染类来保存和控制 一个国家

使用无渲染类:

保持一个应用的状态,没关系!

控制一个应用程序的状态,这将正确地导致您的 ReactJS 应用程序出现问题。

【讨论】:

    【解决方案2】:

    尝试将道具作为对象发送给您的孩子,该对象只会发送您可以轻松处理的对象的引用。尽管如果两个子组件继承相同的状态,那么您需要将原始值作为道具发送。保持一个应用程序的状态很好。休息是根据您的要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-28
      • 2021-09-11
      • 2018-01-02
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 2017-06-17
      相关资源
      最近更新 更多