我怎样才能在React.js重构这些变量
问题描述:
林学习React.js和林不知道在做如下的最佳方式:我怎样才能在React.js重构这些变量
我有以下类做出反应(精简为简单起见)
const X01Game = React.createClass({
saveShot(e) {
e.preventDefault();
const currentPlayer = this.props.players[this.state.currentPlayer],
currentID = currentPlayer.ID,
shot = this.refs.shot.value;
.... shot saved.....
},
isValidShot(shot) {
const currentPlayer = this.props.players[this.state.currentPlayer],
currentID = currentPlayer.ID,
score = this.state.score[currentID];
.... shot validated.....
},
render() {
return (
<div className="game-container">
.... render game ....
</div>
);
}
});
export default X01Game;
正如你可以用几种方法看到我重复这个:
const currentPlayer = this.props.players[this.state.currentPlayer],
currentID = currentPlayer.ID,
shot = this.refs.shot.value;
有什么办法可以在全球范围宣布这些所谓避免重复每个方法?不看我的权利这样
答
因为你总是请求currentPlayerId
,只需添加一个方法到X01Game class
将得到它:
getGurrentPlayerId() {
var currentPlayer = this.props.players[this.state.currentPlayer];
return currentPlayer ? currentPlayer.id : null; // in case the player doesn't exist
}
这同样适用于拍摄:
getShot() { // pun intended
return this.refs.shot && this.refs.shot.value;
}
现在你可以这样做:
saveShot(e) {
e.preventDefault();
const currentID = this.getGurrentPlayerId(),
shot = this.getShot();
.... shot saved.....
},
isValidShot(shot) {
const currentID = this.getGurrentPlayerId(),
score = this.state.score[currentID];
.... shot validated.....
},
我不认为这将是理想的,现在他已经添加了两个额外的方法,但不添加任何代码缩减,您只需从 – David
中提取抽取数据的位置。抽象为DRY,因为它们可以多次使用,无需重复自己。 'getGurrentPlayerId'还封装了获取'currentPlayerId'的逻辑,所以你可以在获取id之前跳过找到'currentPlayer'(2行而不是4行)。 –
感谢@OriDrori这将成为我的下一个自然步骤,我只是想知道我们是否可以设置更全局的东西,比如当您在PHP类的构造函数上设置变量时 – chifliiiii