首页 文章

反应非状态组件以某种方式通过状态

提问于
浏览
1

不知何故,我不小心在React中设置了“ownee”组件的状态 . 我相信我只传递道具,但是当我查看React Dev Tools控制台中的组件时,我看到所有者的初始状态是作为道具正确传递的,但不知何故,当我在“setState”中调用“setState”时所有者,然后它作为状态传递给ownee .

奇怪的是,在我添加“activePlayer”状态/道具之前,这个相同的代码运行良好 . 如果它有任何区别,“activePlayer”是对“player”数组中的一个玩家的对象引用 .

这是所有者的代码:

var App = React.createClass({
  getInitialState: function(){
    return{
      players: [],
      neck: [],
      activePlayer: null
    }
},

componentDidMount(){
    self = this;

    socket.on("pass initial state", function(data){
      self.setState({players: data.players, 
                  neck: data.neck,
                  activePlayer: data.activePlayer})
      }) 

    socket.on('new player added', function(data){
      self.setState({players: data.players});
      })

    socket.on('game started', function(data){
      self.setState({neck: data.neck,
                activePlayer: data.activePlayer})
    })
  },

render: function () {
    return (
      <div id='App'>
        <OpponentsDIV players={this.state.players} activePlayer={this.state.activePlayer}/>
  </div>)}
    });

module.exports = App;

ReactDOM.render(<App />, document.getElementById('main-container'));

而这里是“ownee”(OpponentsDIV)

var OpponentsDIV = React.createClass({
  render: function () {
    self = this;

    var playerList = this.props.players.map(function(player){
        var key = "playerDIV"+ player.name;
      var active = false;
      if (self.props.activePlayer === player.name){
        active = true;
      };
        return <PlayerDIV player={player} key={key} active={active}/>
    });

    return (
      <div  className="layoutDIV" id='OpponentsDIV'>
        OpponentsDIV
        {playerList}
        <ChatDIV />
      </div>
    )
  }
});

module.exports = OpponentsDIV;

1 回答

  • 0

    我想通了:因为我错过了声明中的“var”:

    self = this;
    

    在OpponentsDIV中,我认为我的“自我”和/或“这个”变量的范围是重叠的,导致React认为“自我”是指OpponentsDIV而不是App .

    解决方法是简单地将“var”放在OpponentsDIV第3行的语句前面 . 我可以通过简单地添加或删除“var”来一致地重现修复和破坏代码 . 啊,Javascript .

相关问题