我的应用程序的一部分具有以下结构,我正在尝试类似于棋盘游戏。 tile是对象{color1,color2,key},HexTile是显示tile的React组件。
class HexTile extends Component{
constructor(props) {
super(props);
let { color1, color2, key } = props.tile;
let tile = [color1, color2];
// Initialize hexagons with some color
const hexagons = GridGenerator.orientedRectangle(2, 1).map((hexagon, index) => {
return Object.assign({}, hexagon, {
color: tile[index],
tile: key
});
});
this.state = {
hexagons,
...
};
}
static propTypes = {
...,
tile: PropTypes.object.isRequired,
...
};
render() {
const { hexagons } = this.state;
return (
<Layout className="tile" size={{ x: 3, y: 3 }} flat={false} spacing={1.01}
origin={{ x: this.props.x, y: this.props.y }}>
{
hexagons.map((hex, i) => (
<Hexagon
key={i}
...
data={hex}
>
</Hexagon>
))
}
</Layout>
);
}
TileList是一个组件,它接收一个tile列表作为props,将其保存在其状态并呈现每个tile:
class TileList extends Component{
constructor(props){
super(props);
this.onDragEnd = this.onDragEnd.bind(this);
const { tiles } = props;
this.state = {
...,
tiles: tiles
};
}
render() {
const { tiles } = this.state;
return (
<g>
{
tiles.map((tile, i) => (
<HexTile key={i}
...
tile={tile}
onDragEnd={this.onDragEnd}
...
/>
))
}
</g>
);
}
app是主要组件,它会将tile列表保存在其状态并呈现TileList,也会在使用tile时更新它,并为新Tile更改它。
class App extends Component {
constructor(props){
super(props);
// Event where the tile list is updated, this is working
this.onDragEnd = this.onDragEnd.bind(this);
...
const playerTiles = App.generateTiles(6);
this.state = {
...
playerTiles,
};
}
render() {
const { playerTiles, ... } = this.state;
return (
<div className="app">
<HexGrid width={1200} height={800} viewBox="-50 -30 50 100">
...
<TileList className={'tiles'}
tiles={playerTiles}
onDragEnd={this.onDragEnd}
...
/>
</HexGrid>
...
</div>
);
}
App和TileList之间的状态更新正在运行,但HexTile上应该更新的磁贴与开头相同,我不知道如何更新它。我不包括生成更新的事件,因为它包含其他功能,但如果需要,我会添加它。尽管如此,我认为问题在于HexTiles的初始化,但我还没弄清楚如何修复它。
答案 0 :(得分:1)
您需要使用新的道具数据更新六边形。尝试在componentWillReceiveProps
中更新您的州:
componentWillReceiveProps(prevProps, nextProps){
const { color1, color2, key } = nextProps.tile;
const tile = [color1, color2];
// Initialize hexagons with some color
const hexagons = GridGenerator.orientedRectangle(2, 1).map((hexagon, index) => {
return Object.assign({}, hexagon, {
color: tile[index],
tile: key
});
});
this.state = {
hexagons,
...
};
}