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