Paw*_*cki 4 javascript filtering reactjs react-redux
这可能是一个克隆帖子,但在我的情况下我没有找到任何解决方案。我有一个对象列表:
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'}
]
}
Run Code Online (Sandbox Code Playgroud)
我将其导入到组件,分配给状态并在下面的组件中显示。
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);
Run Code Online (Sandbox Code Playgroud)
清单看起来像这样
问题是我想按输入值过滤我的球员名单。我在这里做了一些研究,只在Array中发现了过滤,而不像在Objects列表中那样。
我现在所做的是:
谢谢大家!我已移除玩家状态
constructor(props){
super(props);
this.state = {
//players: this.props.players <-- Stupid thing
player: '' //empty to set as an input
}
}
Run Code Online (Sandbox Code Playgroud)
并重写我的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>
);
})
}
Run Code Online (Sandbox Code Playgroud)
this.state.players.filter(player => player.name.includes(this.state.player))
Run Code Online (Sandbox Code Playgroud)
如果您想映射它们而不是仅过滤状态...
this.state.players.filter(player =>
player.name.includes(this.state.player)).map(searchedPlayers => {
return(
<tr key={searchedPlayers.name}>
<td>{searchedPlayers.name}</td>
</tr>
);
})
Run Code Online (Sandbox Code Playgroud)
请注意,您也可以直接从道具进行渲染而无需设置状态(以避免每次用户键入时都重新渲染)
this.state.players
Run Code Online (Sandbox Code Playgroud)
与
this.props.players
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6495 次 |
最近记录: |