在 React 中将状态作为 props 向下传递
Passing state down as props in React
我有一个名为 App 的主要组件。
App
像这样拉入 Table
组件
<Table
players={players}
/>
玩家最初在应用程序组件状态中定义为一个空数组。
但在我的 Table
组件中我这样做:
console.log(this.props.players, 'players');
为什么我会得到 undefined?
我的 App 组件中也有这个:
render() {
const { players, matches } = this.state;
关于我对你的问题的评论,你需要做这样的事情:
<Table
players={this.state.players}
/>
这样你就可以从你所在的州获得球员。如果没有 "this.state",您将收到未定义的错误
您应该像这样从 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
组件,那么它应该可以按预期工作,但是
也许您有其他代码段可能会导致此行为。
您没有分享足够的代码让我们知道。
我有一个名为 App 的主要组件。
App
像这样拉入 Table
组件
<Table
players={players}
/>
玩家最初在应用程序组件状态中定义为一个空数组。
但在我的 Table
组件中我这样做:
console.log(this.props.players, 'players');
为什么我会得到 undefined?
我的 App 组件中也有这个:
render() {
const { players, matches } = this.state;
关于我对你的问题的评论,你需要做这样的事情:
<Table
players={this.state.players}
/>
这样你就可以从你所在的州获得球员。如果没有 "this.state",您将收到未定义的错误
您应该像这样从 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
组件,那么它应该可以按预期工作,但是 也许您有其他代码段可能会导致此行为。
您没有分享足够的代码让我们知道。