【发布时间】:2017-12-26 12:23:39
【问题描述】:
在初始Axios 调用后,我在store 中加载了一些数据。
然后我渲染两个组件match(父组件)和player(子组件)。
这是以相关方式显示两个组件的方式(这是我原始代码的简化示例,在此示例中我可以用另一种方式解决我的问题,但在我复杂的实际代码中,必须这样做首先是子组件中的操作):
match.js
class Match extends Component {
constructor(props) {
super(props);
}
render() {
return (
Object.values(this.props.matchs).map(( match_id ) => {
let match = this.props.matchs[match_id];
return (
<div key={match_id}>
<p>{match.tournament}</p>
<p>{match.color}</p> {/* this color depends of children condition*/ }
<div className="players">
{match.array_players.map ( ( player_id ) => {
let player = this.props.players[player_id];
return (
<Player key={odd_id} ownPlayer={player} />
)
})
</div>
</div>
)
});
)
}
}
const mapStateToProps = state => {
return {
matchs: state.matchs.matchs,
players: state.players.players
};
}
const mapDispatchToProps = dispatch => {
return {
// actions
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Matchs);
player.js
class Player extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>{this.props.ownPlayer.name}</p>
<p>{this.props.player_color}</p>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
// I need to make some previous operations before render
let player_color;
if (ownProps.ownPlayer.name == "paul")
player_color = 'yellow';
else
player_color = 'blue';
// Then I Need to update parent component with children color condition
// if (player_color == 'yellow')
// match_color = 'yellow'
//
// Call some action here to update parent component???
// things like these do not work:
// let id_p = ownProps.player.id_player;
// state.players.players[id_p].color = 'blue'; This does not work
return {
player_color
};
};
const mapDispatchToProps = dispatch => {
return {
//
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Player);
然后我需要在子组件中的某些条件之后更新父组件中的道具。
我读过这篇文章:
https://redux.js.org/docs/recipes/ComputingDerivedData.html
但是我不知道如何在渲染之前发送数据来存储和刷新父组件。
我想过像componentWillMount 或componentWillUpdate 中的操作一样调用以将数据发送到存储,但我不知道这是否正确。
【问题讨论】:
-
如果你的子组件直接从它的父组件接收它的两个props(它们是它的变量),那么为什么你不能在父组件内部计算这个父组件的值呢?
-
这是一个简单的例子,但在我的真实代码中,我需要在子项中进行一些复杂的计算,然后根据这些计算更新父组件的颜色(匹配)