【问题标题】:Passing state down as props in React在 React 中将状态作为道具传递
【发布时间】:2018-02-28 15:00:31
【问题描述】:

我有一个名为 App 的主要组件。

App 像这样拉入 Table 组件

<Table
  players={players}
/>

玩家最初在应用组件状态中定义为一个空数组。

但在我的 Table 组件中,我这样做:

console.log(this.props.players, 'players');

为什么我会不确定?

我的 App 组件中也有这个:

render() {
   const { players, matches } = this.state;

【问题讨论】:

  • 你需要作为 this.state.players 传递。它是未定义的,因为玩家在你的状态中,所以你需要 this.state 在玩家之前
  • @GabrielMesquita 啊,我应该说的废话。我的 render() 函数中有 const player = {this.state.players}
  • 哈哈,我明白了。所以这会稍微改变我的答案:)
  • 请发布整个代码,以便我们更好地查看:)
  • 在这种情况下你需要把const {players} = this.state;

标签: javascript reactjs state react-proptypes


【解决方案1】:

关于我在您的问题中的评论,您需要执行以下操作:

<Table
  players={this.state.players}
/>

这样你就可以从你所在的州获得玩家。如果没有“this.state”,您将收到未定义的错误

【讨论】:

    【解决方案2】:

    您应该像这样从state 引用object / array

    this.props.state.players` 
    

    或者你可以像这样使用Destructuring assignment of ES6

     const { players } = this.state;
    

    例子:

    const Table = ({ players }) => {
      return (
        <table>
          <thead>
            <th>Name</th>
          </thead>
          <tbody>
            {
              players.map(player => {
                return (
                  <tr>
                    <td>
                      {player}
                    </td>
                  </tr>
                )
              })
            }
          </tbody>
        </table>
      );
    };
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          players: ['john', 'alex', 'chris', 'dan']
        };
      }
    
      render() {
        const { players } = this.state;
        return (
          <div>
            <Table players={players} />
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    table {
        border-collapse: collapse;
    }
    
    table, th, td {
        border: 1px solid black;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="root"></div>

    编辑
    作为更新问题的后续行动,这实际上取决于您如何设置 Table 组件。

    • 如果它是无状态组件,您应该能够访问播放器 直接不使用this.props.players
    • 如果它是class 组件,那么它应该可以按预期工作,但是 也许您还有其他可能导致此行为的代码。

    您没有分享足够多的代码让我们知道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-30
      • 2019-02-20
      • 1970-01-01
      • 2017-02-23
      • 2016-05-13
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多