如何执行“搜索功能"使用axios从Json调用信息时的反应? [英] How to do a "search function " in react when using axios to call information from Json?
问题描述
我比较陌生,并且在各种情况下练习自己.我正在尝试使用"Axios"从json文件在线调用数据,然后使用搜索过滤出名称.
I am comparatively new to react and is practising myself with various scenarios. I am trying to call data from a json file online using "Axios" and then use search to filter out the names.
但是除了保留组件之外,我无法超越.我确实在网上搜索过有关保留搜索过滤器的信息,但是没有找到适合我的情况的简单/有用的过滤器.伸出援手总是很感激的!
But I am not able to move past except keeping the components. I did search online about keeping an search filter, but was unsuccessful in finding a simple/useful one for my scenario. A helping hand is always appreciated!
我很抱歉,如果这是一个过于简单的问题.
My apologies, if its a too simple question.
import React, { Component } from "react";
import axios from "axios";
class Activities extends Component {
state = {
users: []
};
async componentDidMount() {
const { data: users } = await axios.get(
"https://api.myjson.com/bins/1fj65g"
);
this.setState({ users });
}
render() {
return (
<div>
<h3 style={{ textAlign: "center" }}> Activities</h3>
<div>
{this.state.users.map(user => (
<ul key={user.id} class="list-group card card-1">
<li class="list-group-item">{user.sender.name}</li>
</ul>
))}
</div>
</div>
);
}
}
export default Activities;
这是我在线的json文件.我期待着寻找名字. http://myjson.com/1fj65g
This is my json file online. I am looking forward to search for the names. http://myjson.com/1fj65g
推荐答案
3个步骤.
在JSX中添加一个文本输入节点,并将其onChange
事件绑定到类中的事件处理程序,并将value
绑定到我们将设置的状态值:
Add an text input node in your JSX and bind its onChange
event to an event handler in your class and the value
to the state value we will set :
<input type='text' onChange={this.searchChanged} value={this.state.search}/>
创建一个处理程序以在类中触发onChange
事件时更改您的状态:
Create a handler to change your state when the onChange
event is fired in your class :
searchChanged = event => {
this.setState({ search: event.target.value })
}
最后使用 filter
并在 includes
仅保留与您的过滤器相对应的数据:
And finally use filter
on your array and includes
to only keep the data corresponding to your filter :
{this.state.users
.filter(user => user.name.includes(this.state.search))
.map(user => (
<ul key={user.id} class="list-group card card-1">
<li class="list-group-item">{user.sender.name}</li>
</ul>
)
)}
这篇关于如何执行“搜索功能"使用axios从Json调用信息时的反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!