gpt4 book ai didi

javascript - 使用 React 过滤对象列表

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:42 25 4
gpt4 key购买 nike

它可能是一个克隆帖子,但我没有找到适合我的情况的任何解决方案。我有一个对象列表:

export default function() {
return [
{name: 'Mark Teer Stegen'},
{name: 'Nelson Semedo'},
{name: 'Gerrard Pique'},
{name: 'Ivan Rakitic'},
{name: 'Sergio Busquets'},
{name: 'Denis Suarez'},
{name: 'Coutinho'},
{name: 'Luis Suarez'},
{name: 'Lionel Messi'},
{name: 'Dembele'},
{name: 'Malcom'}
]
}

我将它导入到组件中,分配给状态并显示在下面的组件中。

import React, {Component} from 'react';
import {connect} from 'react-redux';

class Barca extends Component{
constructor(props){
super(props);

this.state = {
players: this.props.players,
player: '' //empty to set as an input
}
}

onChange(e){
this.setState({
player: e.target.value
});
console.log(this.state.player);
}
renderList(){
return this.state.players.map((player) => {
return(
<tr key={player.name}>
<td>{player.name}</td>
</tr>
);
});
}
render(){
return(
<div className="col-sm-6 table-col table-responsive">
<input
type="text"
value={this.state.player}
onChange={this.onChange.bind(this)}
/>
<table className="table table-striped">
<thead>
<tr>
<th className="text-center">
FC Barcelona
</th>
</tr>
</thead>
<tbody>
{this.renderList()}
</tbody>
</table>
</div>
);
}
}

const mapStateToProps = (state) => {
return {
players: state.reducerBarca
};
};


export default connect(mapStateToProps)(Barca);

列表看起来像那样

list view

问题是我想根据输入的值过滤我的玩家列表。我在这里做了一些研究,我只在 Array 中发现了过滤,而不是在 Objects list 中。

我现在做了什么:

  1. 显示玩家列表
  2. 从输入中获取值并在每个写入的字母后显示它
  3. 如何通过输入的术语呈现我的列表???

谢谢大家!我已经删除了玩家状态

constructor(props){
super(props);

this.state = {
//players: this.props.players <-- Stupid thing
player: '' //empty to set as an input
}
}

并重写我的renderList() 函数

return this.props.players.filter(player =>
player.name.toLowerCase().includes(this.state.player.toLowerCase())).map(searchedPlayers => {
return(
<tr key={searchedPlayers.name}>
<td>{searchedPlayers.name}</td>
</tr>
);
})
}

最佳答案

this.state.players.filter(player => player.name.includes(this.state.player))

如果您想映射它们而不是仅仅过滤状态...

this.state.players.filter(player => 
player.name.includes(this.state.player)).map(searchedPlayers => {
return(
<tr key={searchedPlayers.name}>
<td>{searchedPlayers.name}</td>
</tr>
);
})

请注意,您也可以直接从 props 渲染而无需设置状态,(以避免每次用户输入时都重新渲染)通过替换

this.state.players

this.props.players

关于javascript - 使用 React 过滤对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51901124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com