Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React中搜索筛选器?_Javascript_Reactjs_Filter_Axios - Fatal编程技术网

Javascript 在React中搜索筛选器?

Javascript 在React中搜索筛选器?,javascript,reactjs,filter,axios,Javascript,Reactjs,Filter,Axios,我一直在尝试很多不同的解决方案,但迄今为止没有一个有效。我想在输入字段中过滤从API获取的数据。我把数据放在一个我称之为peopleList的列表中,这就是我要筛选的列表 以下是来自Api的数据: 和代码: import React from 'react' import axios from 'axios' class List extends React.Component { constructor(props) { super(props) this.state =

我一直在尝试很多不同的解决方案,但迄今为止没有一个有效。我想在输入字段中过滤从API获取的数据。我把数据放在一个我称之为
peopleList
的列表中,这就是我要筛选的列表

以下是来自Api的数据:

和代码:

import React from 'react'
import axios from 'axios'

class List extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      peopleList: [], // here the empty list
      search: '',
    }
  }

  componentDidMount() {
    this.peopleListFromApi()
  }

  peopleListFromApi() {
    const baseUrl = 'https://swapi.dev/api/'

    axios.get(baseUrl + 'people').then((response) => {
      let peopleList = response.data.results.map((person, i) => {
        return (
          <main key={i}>
            <ul key={i}>
              {
                <li key={i}>
                  {'(' +
                    person.gender +
                    ') ' +
                    person.name +
                    ' is ' +
                    person.height +
                    ' cm tall, got ' +
                    person.eye_color +
                    ' eyes and is born ' +
                    person.birth_year}
                </li>
              }
            </ul>
          </main>
        )
      })
      this.setState({ peopleList: peopleList }) // here i update it with the data from api
    })
  }

  onchange = (event) => {
    this.setState({ search: event.target.value })
  }

  render() {
    return (
      <main>
        <ul>
          {this.state.peopleList} {/* write it out on screen */}
        </ul>
        <input
          className="search"
          placeholder="Search the universe..."
          type="text"
          value={this.state.search}
          onChange={this.onchange}
        ></input>
      </main>
    )
  }
}

export default List
从“React”导入React
从“axios”导入axios
类列表扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
peopleList:[],//这里是空列表
搜索:“”,
}
}
componentDidMount(){
this.peopleListFromApi()
}
peopleListFromApi(){
常量baseUrl=https://swapi.dev/api/'
get(baseUrl+‘people’)。然后((响应)=>{
让peopleList=response.data.results.map((person,i)=>{
返回(
    {
  • {'(' + 个人性别+ ') ' + 人名+ “是”+ 人身高+ '厘米高,有'+ 人眼颜色+ “眼睛和出生”+ 人.出生_年}
  • }
) }) this.setState({peopleList:peopleList})//这里我用api中的数据更新它 }) } onchange=(事件)=>{ this.setState({search:event.target.value}) } render(){ 返回(
    {this.state.peopleList}{/*在屏幕上写出来*/}
) } } 导出默认列表
以下是可用于筛选数据的代码片段:

  const filterNames = ({ name }) => {
    return name.toLowerCase().indexOf(searchValue.toLowerCase()) !== -1;
  };

  return (
    <div className="App">
      <h2>Search</h2>
      <SearchBar onSearch={setSearchValue} value={searchValue} />
      <ul>
        {users.filter(filterNames).map((user) => {
          return <li key={user.id}>
            {user.name}
          </li>
        })}
      </ul>
    </div>
  );
const filterNames=({name})=>{
返回name.toLowerCase().indexOf(searchValue.toLowerCase())!=-1;
};
返回(
搜寻
    {users.filter(filterNames).map((用户)=>{ return
  • {user.name}
  • })}
);

让用户=[
{
姓名:'riyas',
年龄:31
},
{
名称:“testuser”,
年龄:22
},
{
名称:“testuser123”,
年龄:22
}
];
类测试扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
用户:用户,,
结果:用户,
};
this.filterList=this.filterList.bind(this);
}
组件将接收道具(下一步){
这是我的国家({
用户:nextrops.users,
});
}
过滤器列表(事件){
让值=event.target.value;
让users=this.state.users,结果=[];
结果=用户。筛选器((用户)=>{
返回user.name.toLowerCase().search(值)!=-1;
});
this.setState({result});
}
render(){
const userList=this.state.result.map((用户)=>{
返回
  • {user.name}{user.age}
  • ; }); 返回(
      {userList}
    ); } } ReactDOM.render(,document.getElementById('app'))

    这是一个使用文本框过滤数据的示例。步骤1:将json数据存储在API响应中接收到的状态:

    peopleListFromApi = () => {
      const baseUrl = 'https://swapi.dev/api/'
      axios.get(baseUrl + 'people').then((response) => {
        const peopleList = response.data.results || []
        this.setState({ peopleList: peopleList })
      })
    }
    
    onchange = (event) => {
      this.setState({ search: event.target.value })
    }
    
    filterFunction = (people) => {
      return people.name.toUpperCase().indexOf(this.state.search.toUpperCase()) > -1
    }
    
    步骤2:过滤并在UI中显示:

    render() {
      return (
        <main>
          <ul>
            {this.state.peopleList.filter(this.filterFunction).map((filtered, i) => (
              <li key={i}>
                {/* You can use: key={filtered.id} if it exists */}
                {'(' +
                  filtered.gender +
                  ') ' +
                  filtered.name +
                  ' is ' +
                  filtered.height +
                  ' cm tall, got ' +
                  filtered.eye_color +
                  ' eyes and is born ' +
                  filtered.birth_year}
              </li>
            ))}
          </ul>
          <input
            className="search"
            placeholder="Search the universe..."
            type="text"
            value={this.state.search}
            onChange={this.onchange}
          ></input>
        </main>
      )
    }
    
    render(){
    返回(
    
      {this.state.peopleList.filter(this.filterFunction).map((filtered,i)=>(
    • {/*如果存在,可以使用:key={filtered.id} {'(' + A.性别+ ') ' + 过滤的名称+ “是”+ 过滤高度+ '厘米高,有'+ 过滤的眼睛颜色+ “眼睛和出生”+ 过滤。出生_年}
    • ))}
    ) }
    根据哪些字段过滤数据?我认为您只需要使用
    过滤器
    数组函数手动进行过滤。如果不想编写自己的实现,请查看fusejs。。它易于配置,速度非常快,并且有很多选项。我尝试过使用过滤器阵列功能,但我不知道如何连接它,我很新的反应,所以我很困惑。。。我可以得到一些关于如何继续在渲染函数中编写步骤2的提示吗?还是全部写在.then()中?当我试图将filterFunction放在render()函数中时,我得到了“预期的赋值或函数调用,却看到了一个表达式”?非常感谢Ajeet,帮了我很多忙!如果我还有什么问题,我可以@you吗?
    render() {
      return (
        <main>
          <ul>
            {this.state.peopleList.filter(this.filterFunction).map((filtered, i) => (
              <li key={i}>
                {/* You can use: key={filtered.id} if it exists */}
                {'(' +
                  filtered.gender +
                  ') ' +
                  filtered.name +
                  ' is ' +
                  filtered.height +
                  ' cm tall, got ' +
                  filtered.eye_color +
                  ' eyes and is born ' +
                  filtered.birth_year}
              </li>
            ))}
          </ul>
          <input
            className="search"
            placeholder="Search the universe..."
            type="text"
            value={this.state.search}
            onChange={this.onchange}
          ></input>
        </main>
      )
    }