道具更改时重新渲染 React 组件?

新手上路,请多包涵

我有一个带有 Mobx 存储的 React 组件,如下所示:

 class Board extends Component {
  componentDidMount() {
    this.props.dataStore.getSinglePlayer(1)
    this.props.squareStore.getAllSquares()
  }

  componentWillReceiveProps(nextProps) {
    if (
      this.props.dataStore.currentPlayer !==
      this.nextProps.dataStore.currentPlayer
    ) {
      this.nextProps.dataStore.getSinglePlayer(1)
    }
  }

  randomNumber() {
    return Math.floor(Math.random() * 6) + 1
  }

  roll(playerId, playerPosition) {
    let dice1 = this.randomNumber()
    let dice2 = this.randomNumber()

    let totalRoll = dice1 + dice2
    let totalPosition = totalRoll + playerPosition
    this.props.dataStore.changeUserPosition(playerId, totalRoll)
    document.getElementById('dice').innerHTML =
      'You rolled ' + totalRoll + '!  You are now on ' + totalPosition
  }

  render() {
    var player = {
      name: '',
      id: '',
      position: 0
    }
    console.log(this.props.dataStore.currentPlayer)
    if (this.props.dataStore.currentPlayer) {
      var currentPlayer = this.props.dataStore.currentPlayer
      player = {
        name: currentPlayer.name,
        id: currentPlayer.id,
        position: currentPlayer.position
      }
    }
    if (this.props.squareStore.squares) {
      var squares = this.props.squareStore.squares.map((square, i) => {
        var movement

        if (i == player.position) {
          movement = **
        }
        return (
          <li key={i}>
            <span>
              {square.title}
              <br />
              {movement}
              {square.price}
            </span>
          </li>
        )
      })
    } else {
      squares = <h4>Squares being loaded...</h4>
    }

    return (
      <div>
        <h1>Player: {player.name}</h1>
        <h2>Roll Dice!</h2>
        <button onClick={() => this.roll(player.id, player.position)}>
          Roll
        </button>{' '}
        <h1 id="dice">{}</h1>
        <div className="board">
          <ul>{squares}</ul>
        </div>
      </div>
    )
  }
}

export default inject('dataStore', 'squareStore')(observer(Board))

单击按钮时,this.props.dataStore.currentPlayer.position 会更新为新值。但是,此新值仅在手动刷新页面时显示。有没有办法告诉组件值已经改变并且它应该自动重新渲染?

原文由 Nespony 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 194
1 个回答

React.Component 生命周期 => 更新

更新可能是由道具或状态的变化引起的。

这意味着如果你想重新渲染你的组件,你需要:

  • 使用 this.setState({ }) 方法更新组件状态
  • 或将更新的 props 从父级传递给该组件
  • 或者,如果您正在使用 Redux/MobX 作为状态管理器,您需要更新存储,因此连接 props 将被更新并且 re-render 将被触发–

原文由 YUzhva 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题