繁体   English   中英

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

[英]React - How can I access a state/array that's in one .js file in a different .js file?

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 中的板重置回所有问号问题是,我需要访问“this.state”来自 Board.js 的板。 我知道这条线

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

不起作用,因为我不完全理解访问该数组所需的语法。 我怎样才能访问第一个数组,以便我可以将它改回所有问号? 谢谢!

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

有两个选项可以解决您的问题:

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

正如 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>
    )
  }
}

接口.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM