我想传递两个对象(已编辑)作为道具,我想像子对象this.state.time1
中访问它们,而不是this.state.timeInfo.time1
。那可能吗?
我在构造函数中尝试过this.state = { ...props.clockInfo, ...props.gameState };
,但是当props.gameState
更改时,孩子的状态不会更新。
编辑:
此函数更改父组件和子组件的prop的状态,但不更改子组件的状态。
startGame = () => {
let gameState = {
myTurn: true,
myColor: 0,
gameStarted: true,
gameEnded: false
};
this.setState({
gameState: gameState
});
console.log(this.state);
};
<ChessClock clockInfo={this.props.clockInfo} gameState={this.state.gameState} onRef={ref => (this.child = ref)} />
子组件(很多console.logs,因为我尝试调试此组件)
constructor(props) {
super(props);
this.state = { ...props.clockInfo, ...props.gameState };
console.log("@@@@@@@@@@@@@@@@");
console.log(props);
console.log(this.state);
}
render() {
return (
<div className="row text-center w-100 GUI_clocks">
<div className="h2 col">
{this.state.time1 / 60 - ((this.state.time1 / 60) % 1)}:{this.state.time1 % 60 < 10 ? "0" + (this.state.time1 % 60) : this.state.time1 % 60}
</div>
<div className="h2 col">
{this.state.time2 / 60 - ((this.state.time2 / 60) % 1)}:{this.state.time2 % 60 < 10 ? "0" + (this.state.time2 % 60) : this.state.time2 % 60}
</div>
</div>
);
}
componentWillReceiveProps() {
console.log("CHESS CLOCK COMPONENT WILL RECEIVE PROPS");
console.log(this.state);
console.log(this.props);
//this.setState(...this.props.gameState, ...this.props.clockInfo);
}
componentDidUpdate() {
console.log("CHESS CLOCK DID UPDATE");
console.log(this.state);
console.log(this.props);
}
componentDidMount() {
this.props.onRef(this);
}
componentWillUnmount() {
this.props.onRef(undefined);
}
startStopClock() {
if (this.props.myTurn && this.props.gameStarted && this.timerID == null) {
this.timerID = setInterval(() => {
if (this.state.myPlayerNumber === 1) {
this.setState({ time1: this.state.time1 - 1 });
} else {
this.setState({ time2: this.state.time2 - 1 });
}
}, 1000);
}
if (!this.props.myTurn || !this.props.gameStarted) {
if (this.timerID != null) {
clearInterval(this.timerID);
this.timerID = null;
console.log("cleaned interval; " + this.timerID);
}
}
}
}```