ReactJS:重新加载组件的新实例吗?

时间:2018-12-19 10:53:18

标签: reactjs

我希望我能够以一种可以理解的方式来解释我的问题。

我对React非常陌生!而且我还不知道如何完成某些事情。

我有一个GamePage组件。在此页面上,我正在渲染GameRound组件。

游戏开始时,新的“游戏回合”开始。比赛结束后,我希望第二回合再开始第三回合。这意味着我需要一种“新” GameRoundGamePage应该保留。

在撰写本文时,我对如何实现这一想法有所了解:在我的gameRoundFinished()事件中,我可以重置GameRound的状态。但这是否已经是最优雅的方法,尤其是Reactive方法?

谢谢。

某些要求的代码...

GamePage.js

export class GamePage extends React.Component {

    constructor(props) {
        super(props);
        // Set game configuration and data
        this.state = {
            gameId: props.match.params.gameId,
            settings: {
                categories: ['Stadt', 'Land', 'Fluss'],
                countdown: 5
            },
            activePlayers: {},
            game: null
        };

        // Open socket
        this.socket = openSocket('http://localhost:3000');

        this.socket.emit('join', this.state.gameId);

        this.socket.on('updatePlayers', players => {
            this.state.activePlayers = players;
            this.setState(this.state);
        });

        this.socket.on('startGame', () => {
            this.state.game = {
                rounds: []
            };
            this.state.game.rounds.push({

            });
            this.setState(this.state);
        });
    }

    onClick = () => {
        this.socket.emit('ready');
    }

    render() {
        if (this.state.game) {
            return (
                <GameRound socket={this.socket} config={this.state}></GameRound>
            );
        } else {
            return (
                <div>Currently {this.state.activePlayers.length}/3
                <Button onClick={this.onClick}>klick</Button></div>
            );
        }
    }
}

GameRound.js

export class GameRound extends React.Component {
    // too much code that is irrelevant for the question

    render() {
        return ...
    }
}

3 个答案:

答案 0 :(得分:1)

A very simple way to "reset" a component (and re-run the constructor) is to use the key prop. See https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

In your case: be sure to provide a new key at every round change: something like:

<GameRound key={roundId} socket={this.socket} config={this.state}></GameRound>

答案 1 :(得分:0)

在进行其他操作之前,有必要清除代码:

要在render方法中将函数与合成事件一起调用:

<Button onClick={this.onClickEvent()}>click</Button></div>

使用this.setState({ a: 123 })更改this.state对象,而不使用this.state本身更改状态。

很好的例子:

this.setState({ activePlayers: players });

错误的例子

this.setState(this.state);
this.state.game = { rounds: [] };
this.state.game.rounds.push({ ... });

您可能要使用socket.on()函数来更改状态,如下所示:

socket.on(){
  ...
  this.setState({ activePlayers: players });
}

<Button onClick={this.socket.on()}>click</Button></div>

答案 2 :(得分:0)

一种解决方案是设计GameRound,使其接受道具来确定其行为。然后要“重置”,只需为道具传递适当的值即可将其设置为新回合。

相关问题