gpt4 book ai didi

javascript - Prop 更改时重新渲染 React 组件?

转载 作者:行者123 更新时间:2023-11-30 08:23:59 25 4
gpt4 key购买 nike

我有一个带有 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 会更新为新值。但是,此新值仅在手动刷新页面时显示。有没有办法告诉组件值已更改并且它应该自动重新呈现?

最佳答案

React.Component Lifecycle => Updating

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

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

  • 使用 this.setState({ }) 方法更新组件状态
  • 或者将更新的 props 从父组件传递给该组件
  • 或者如果你使用 Redux/MobX 作为状态管理器,你需要更新存储,所以连接的 props 将被更新并 重新渲染 将被触发

关于javascript - Prop 更改时重新渲染 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48607560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com