我有一个看起来像这样的数组:
const teamsAndPlayers = [
{
team: 'Liverpool',
players: ['Salah', 'Henderson']
},
{
team: 'Man Utd',
players: ['Rashford', 'De Gea']
},
{
team: 'Chelsea',
players: ['Hazard', 'Willian']
}
];
我有2个选择框,其中第二个是基于用户选择的动态框。我遇到的问题是我不确定根据用户选择来找到相关阵列的最佳方法。我知道我可以使用find
和其他方法,但是无论如何,我可以在return语句的map
函数中完成所有操作吗?
我的代码如下:
const Menu = () => {
const [selectedTeam, setSelectedTeam] = useState(null);
return (
<div>
<select
onChange={e => setSelectedTeam(e.target.value)}
id="team"
name="team"
>
{teamsAndPlayers(item => (
<option key={item.team} value={item.team}>
{item.team}
</option>
))}
<select id="players" name="players">
{teamsAndPlayers(item => (
// how can I get the related players in here
// based on first select choice?
))}
</div>
)
}
答案 0 :(得分:6)
我将使用对象而不是数组来定义选择的输入(如果您真的想避免使用find )。
因此teamsAndPlayers
看起来像这样:
const teamsAndPlayers = {
liverpool: {
name: 'Liverpool',
players: ['Salah', 'Henderson']
},
manUtd: {
name: 'Man Utd',
players: ['Rashford', 'De Gea']
},
chelsea: {
name: 'Chelsea',
players: ['Hazard', 'Willian']
}
};
然后fisrt select中的选项如下所示:
{Object.keys(teamsAndPlayers).map(key => (
<option key={key} value={key}>
{teamsAndPlayers[key].name}
</option>
))}
然后第二个选择中的选项如下:
{teamsAndPlayers[selectedTeam].players.map(player => (
<option key={player} value={player}>
{player}
</option>
))}
答案 1 :(得分:1)
只需结合const item = [{
verDiv: 'div-gpt-ad-1553003087342-0',
verKv: 'version1',
verSize: [300, 250],
weight: 10 //should be chosen in 10% of cases
},
{
verDiv: 'div-gpt-ad-1553003087342-1',
verKv: 'version2',
verSize: [300, 250],
weight: 25 //should be chosen in 25% of cases
},
{
verDiv: 'div-gpt-ad-1553003087342-2',
verKv: 'version3',
verSize: [160, 600],
weight: 25 //should be chosen in 25% of cases
},
{
verDiv: 'div-gpt-ad-1553003087342-3',
verKv: 'version4',
verSize: [728, 90],
weight: 40 //should be chosen in 40% of cases
}];
const randomItem = (item) => {
const stat_map = []
item.map((v, i) => stat_map.push(...new Array(v.weight).fill(i)))
const rand = Math.floor(Math.random() * stat_map.length)
return item[stat_map[rand]]
}
console.log(randomItem(item))
和find
(如果您不想更改数据数组结构):
map