访问ReactJS中的文件之间的状态

问题描述 投票:0回答:1

我试图向我学习一些React,但似乎无法理解它。 我如何在newMove()中访问this.state.planet? 未捕获的TypeError:无法读取未定义属性'state'是我得到的。

这是app.js.

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = newPlay();
  }

  render() {
    return (
      <div>
        <button onClick={(e) => newMove(e)}>New Move</button>
      </div>
    );
  }
}

这是logic.js

export const newPlay = () => ({
  planet: 'Earth',
  position: [0, 0, 0, 0, 0, 0, 0, 0, 0],
  active: true,
  shots: 5
});

export const newMove = () => {
  let player = this.state.planet === 'Earth' ? 'Human' : 'Alien';
  console.log(player);
  this.setState({
    shots: this.state.shots++,
    active: false
  })
}
javascript reactjs
1个回答
2
投票

要使this在newMove函数中按预期工作,必须将它绑定到构造函数方法中的类实例this

请注意,您不能对newMove使用箭头表示法语法。箭头功能不支持重新绑定this。请改用function

export function newMove() { 
  ...
}

然后在App类中绑定它,并在onClick prop中使用绑定的this.newMove

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = newPlay();
    this.newMove = newMove.bind(this); 
  }

  render() {
    return (
      <div>
        <button onClick={this.newMove}>New Move</button>
      </div>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.