当props改变时重新渲染 React 组件?

IT技术 javascript reactjs mobx
2021-05-26 23:50:15

我有一个带有 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 用一个新值更新。然而,这个新值仅在页面被手动刷新时显示。有没有办法告诉组件值已经改变,它应该自动重新渲染?

4个回答

React.Component 生命周期 => 更新

更新可能由props或状态的更改引起。

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

  • 使用this.setState({ })方法更新组件状态
  • props从父级传递更新到该组件
  • 或者如果你是Redux/MobX作为状态管理器使用,你需要更新商店,所以连接props将被更新并被re-render触发

您应该考虑使用state以便setState重新渲染您的组件。我建议重构您的代码,尤其是您的render. 我认为您的播放器应该是状态,因为每次点击都会更改一些参数(当前播放器 ID、名称和位置)。请注意不要直接设置您的状态,render因为这可能会导致无限循环,并且render应该始终保持纯方法。所以这需要更认真的重构。此外,通常没有必要在没有状态甚至没有构造函数的情况下使用有状态组件!

无论如何,这里我们只是setStatetotalPosition ,这可能对您有用,但您应该考虑优化您的组件。

class Board extends Component {
constructor(props){
 super(props);
 this.state = {
 totalPosition: null
 }
}
  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
    this.setState({
      totalPostion: totalRoll + playerPosition
    });
    let totalPosition = totalRoll + playerPosition
    this.props.dataStore.changeUserPosition(playerId, totalRoll)
    document.getElementById('dice').innerHTML =
      'You rolled ' + totalRoll + '!  You are now on ' + this.state.playerPostion
  }

  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))
<button onClick={() => this.roll(player.id, player.position); this.forceUpdate()}>

我相信您没有正确设置这种交互。我没有使用过 MobX,但是这样做的react方式是改变props。如果你有一个环绕它的包装组件监听 store 上的变化,并将数据传递到 Board,它会自动更新。我认为这个MobX 连接包对你非常有用。