在我的React组件中,我有数组和对象:
topPlayers: [
{Name: 'User1', ...},
{Name: 'User2', ...}
]
players: {
User1: {},
User2: {},
...
}
我两个都处于状态,在我看来,我想显示topPlayers列表,以及来自players
数组的关于他们的其他信息。
render() {
return(
{Object.keys(this.state.topPlayers).map((key, i) => (
<div key={i}>
<span>{this.state.topPlayers[key].Name}</span>
<span>{this.state.topPlayers[key].Points}</span>
<span></span>
</div>
))}
)
}
,在最后一个span
中,我想从this.state.players[this.state.topPlayers[key].Name]
之类的玩家数组中绑定字段,但这不起作用。我在React中很新,所以我不明白自己做错了什么。
我将非常感谢您的帮助或任何提示。
答案 0 :(得分:1)
您的class MyGeneric<T> { }
type ReplaceType<T> = [T] extends [Function] ? T : MyGeneric<T> | T;
// Input type: string
// Expected type: string | MyGeneric<string>
// Actual type: string | MyGeneric<string>
type Test1 = ReplaceType<string>;
// Input type: () => void
// Expected type: () => void
// Actual type: () => void
type Test2 = ReplaceType<() => void>;
// Input type: boolean
// Expected type: boolean | MyGeneric<boolean>
// Actual type: boolean | MyGeneric<boolean>
type Test3 = ReplaceType<boolean>;
// Input type: "foo" | "bar"
// Expected type: "foo" | "bar" | MyGeneric<"foo" | "bar">
// Actual type: "foo" | "bar" | MyGeneric<"foo" | "bar">
type Test4 = ReplaceType<"foo" | "bar">;
状态只是一个数组,因此您可以直接在其上使用topPlayers
。您可以直接在map
对象上使用顶级玩家的Name
作为键。
示例
players
class App extends React.Component {
state = {
topPlayers: [{ Name: "User1" }, { Name: "User2" }],
players: {
User1: { description: "foo" },
User2: { description: "bar" }
}
};
render() {
const { topPlayers, players } = this.state;
return (
<div>
{topPlayers.map((player, i) => (
<div key={i}>
<span>{player.Name}: </span>
<span>{players[player.Name].description}</span>
</div>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));