Go Channel Practice IV - Token Bucket
React - 组件和 props

React - Tic Tac Toc

violet posted @ Jul 16, 2020 07:48:17 AM in 读书笔记 with tags React , 284 阅读

在 react 中,数据通过 props 传递,从父组件流向子组件。
可以通过 react 组建的构造函数中设置 this.state 来初始化 state,this.state 应该被视为一个组件的私有属性。
在 js class 中,每次定义子类的构造函数时,都需要调用 super 方法。因此在所有含有构造函数的 react 组件中,构造函数必须以 super(props) 开头。
在 render 中 onClick 事件监听函数中调用 this.setState, 就可以在每次 <button> 被点击的时候同志 react 去重新渲染 Square 组件。组件更新之后,Square 组件的 this.state.value 的值会变为 X。每次在组件中调用 setState 时,react 都会自动更新其子组件。
当遇到需要同时获取多个子组件数据,或者两个组件之间需要互相通讯的情况时,需要把子组件的 state 数据提升至其共同的父组件当中保存。之后父组件可以通过 props 将状态数据传递到子组件当中。这样应用当中所有组件的状态数据就能够方便地共享同步了。
在 React 中,有一个命名规范,通常会将代表事件的监听 prop 命名为on[Event], 讲处理事件的监听方法命名为 handle[Event]
不直接修改(或改变底层数据)这种方式和前一种的结果是一样的,好处有几点:

  1. 简化复杂的功能。不可变性使得复杂的特性更容易实现。可以做撤销喝恢复功能。不直接在数据上修改可以让我们追溯并复用游戏的历史记录。
  2. 跟踪数据的改变。如果直接修改数据,则很难跟踪到数据的改变。跟踪数据的改变需要可变对象可以与改变之前的版本进行对比,这样整个对象数都需要被遍历一次。跟踪不可变数据的变化相对来说容易多了。如果发现对象变成了一个新对象,那么我们就可以说对象发生改变了。


每当一个列表重新渲染时,React 会根据每一项列表元素的 key 来检索上一次渲染时与每个 key 所匹配的列表项。如果 react 发现当前的列表又一个之前不存在的 key,那么就会创建出一个新的组件。如果 React 发现和之前对比少了一个 key,那么就会销毁之前所对应的组件。如果一个组件的 key 发生了变化,这个组件会被销毁,然后使用新的 state 重新创建一份。
key 是 react 中一个特殊的保留属性(还有一个是 ref,拥有更高级的特性)。当 React 元素被创建出来的时候,react 会提取出 key 属性,然后把 key 直接存储在返回的元素上。虽然 key 看起来好像是 props 中的一个,但是你不能通过 this.props.key 来获取 可以。 React会用过 key 来自动判断哪些组件需要更新。组件是不能访问到它的 key 的。
每次只要构建动态列表的时候,都要指定一个合适的 key。如果没有找到一个合适的 key,那么就需要重新考虑整理你的数据结构了,这样才能有合适的 key。
如果你没有指定任何 key,react 会发出警告,并且会把数组的索引当作默认的 key。但是如果想要对列表进行重新排序、新增、删除操作时,把数组索引作为 key 是有问题的。显式地使用 key={i} 来指定 key 确实会消除警告,但是仍然和数组索引存在同样的问题,所以大多数情况虾最好不要这么做。
组件的 key 值不需要在全局都保证唯一,只需要在当前的同一级元素之前保证唯一即可。

https://codepen.io/violetzijing/pen/WNrabWw?editors=0010

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null)
      }],
      xIsNext: true,
      stepNumber: 0
    };
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares
      }]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }
  
  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0,
    });
  }
  
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((step, move) => {
      const desc = move ?
            'Go to move #' + move :
            'Go to game start';
      return (
        <li key={move}>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });
 
    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

  • 无匹配
charlly 说:
Dec 29, 2022 03:40:18 PM

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”. React has a few different kinds of components, but they all share one important thing in common: they can all be “rendered” to the screen. When a component is diamond rings rendered, React returns a tree of React elements that describe what should be rendered on the screen.

boardmodelpaper.com 说:
May 04, 2023 12:56:56 AM

we are providing the pdf based on internet search according to past years old examination test and those question bank or study material download and shared based on the internet only.All the Users of the BoardModelPapers can use those boardmodelpaper.com sample papers or Previous Paper Pdf of class-wise study material and blueprint and any for reference purpose only and we are providing the pdf based on internet search according to past years old examination test and those question bank.

model-paper.com 说:
May 04, 2023 12:58:11 AM

In certain cases your mail may be exposed to public that Modelpapers works on giving out better service in different forms and we do not sell or giveaway your personal information other than public info giving out by you. We are very conscious about mail spam model-paper.com and we try to protect every email as much as possible. In certain cases your mail may be exposed to public that Modelpapers works on giving out better service in different forms and we do not sell or giveaway your personal information.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter