React-如何访问另一个.js文件中一个.js文件中的状态/数组?

时间:2020-01-30 23:52:17

标签: javascript reactjs state

export default class Board extends React.Component {
constructor(props) {
    super(props);
    this.state = { board: ['?', '?', '?', '?', '?', '?', '?', '?', '?']};
    this.counter = 0;
    this.limit = 0;
}

我想在其他js文件中使用这些问号(this.state)访问董事会,例如...

import Board from './Board';

export default class Interface extends React.Component
{
constructor(props) {
    super(props);
}

resetBoard()
{
    Board.state.setState({ board: ['?', '?', '?', '?', '?', '?', '?', '?', '?']});
}

render()
{
    return(
        <header id="game-reset">
            <h1 onClick={this.resetBoard}>Reset</h1>
        </header>
    );
}
}

很抱歉遇到难看的格式问题,但实际上我试图使用Interface.js中的resetBoard()函数将Board.js的Board重新设置为所有问号。 问题是,我需要从Board.js访问“ this.state”板。我知道那条线

Board.state.setState({board:['?','?','?','?','?','?','?','?','?']} );

不起作用,因为我不完全了解访问该数组所需的语法。如何访问第一个数组,以便可以将其更改回所有问号?谢谢!

2 个答案:

答案 0 :(得分:0)

在React中无法访问另一个组件的状态。即使有办法-不推荐。

有两种方法可以解决您的问题:

  1. 您可以将状态保留在两个组件的父组件中,并将其(连同必要的功能)作为道具传递给其他组件。
  2. 您可以使用状态管理库,例如Redux或MobX。我会推荐MobX,因为它很简单,但是您应该同时检查一下并自己决定。

答案 1 :(得分:0)

正如Mat在较早的评论中提到的,Component的state属于自己。组件可以通过props将其状态传递给它的子级。

更新父级状态的方法是在父级组件中定义函数,并将其也作为props传递给子级。

因此在您的示例中,它将类似于:

Board.js

class Board extends React.Component {
  constructor(props) {
    super(props);
    this.state = { board: ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']};
    this.counter = 0;
    this.limit = 0;

    this.handleResetBoard = this.handleResetBoard.bind(this);
  }


  handleResetBoard() {
    this.setState({
      board: ['y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y']
    });
  }

  render() {
    return (
      <div>
        <h2>Interface</h2>
        <Interface board={this.state.board} resetBoard={this.handleResetBoard} />
      </div>
    )
  }
}

Interface.js

import Board from './Board';

class Interface extends React.Component {
  constructor(props) {
      super(props);
  }

  render(){
    return(
      <header>
        <pre>{JSON.stringify(this.props.board, null, 2)}</pre>
        <button onClick={this.props.resetBoard}>Button</button>
      </header>
    );
  }
}

查看实际操作:JSFiddle

我也鼓励您在此处阅读更多有关在何处保留状态的信息:https://reactjs.org/docs/thinking-in-react.html#step-4-identify-where-your-state-should-live