Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.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
onChange后的Reactjs搜索_Reactjs_Search_Fetch - Fatal编程技术网

onChange后的Reactjs搜索

onChange后的Reactjs搜索,reactjs,search,fetch,Reactjs,Search,Fetch,我在reactjs应用程序中实现了一些搜索功能。 问题是,我的“searchHandler”函数是在用户在文本字段中输入每个字母后触发的。。。例如,对于术语“Lorem”,我的函数从api中获取了5次:( 我怎样才能解决这个问题 这是我的密码: const { scaleDown } = transitions; function searchingFor(term){ return function(x){ return x.title.toLowerCase().includes(ter

我在reactjs应用程序中实现了一些搜索功能。 问题是,我的“searchHandler”函数是在用户在文本字段中输入每个字母后触发的。。。例如,对于术语“Lorem”,我的函数从api中获取了5次:(

我怎样才能解决这个问题

这是我的密码:

const { scaleDown } = transitions;

function searchingFor(term){

return function(x){
return x.title.toLowerCase().includes(term.toLowerCase()) ||
x.body.toLowerCase().includes(term.toLowerCase());
}

 }  


class ViewAll extends React.Component{

constructor(props){
  super(props);
  this.state = {
    term: '',
    mounted: true,
    tracks: [],
    hasMoreItems: true,
    page: 2,

  }

  this.searchHandler = this.searchHandler.bind(this);
  this.focus = this.focus.bind(this);
  this.keyPress = this.keyPress.bind(this);


 }

  loadContent() {
    var requestUrl = this.props.url;
    fetch(requestUrl + this.state.page + '&_limit=3').then((response)=>{
        return response.json();
    }) .then((tracks)=>{
        this.setState({ tracks: this.state.tracks.concat(tracks)});
        this.setState({page: this.state.page + 1});

        if(this.state.page === 6){
         this.setState({hasMoreItems: false})
       }
    }).catch((err)=>{
        console.log("There has been an error");
    });
}

componentDidMount() {
  window.scrollTo(0, 0);

var requestUrl = this.props.url;
fetch(requestUrl + '1&_limit=3')
    .then((response)=>{
    return response.json();
}) .then((data)=>{
    this.setState({tracks : data});

})
.catch((err)=>{
    console.log("There has been an error");
});

//this.focus();

 }
  searchHandler(event){
    this.setState({term: event.target.value});

    var requestUrl = 'https://questdb.herokuapp.com/all?q='
    fetch(requestUrl + this.state.term).then((response)=>{
        return response.json();
    }) .then((tracks)=>{
        this.setState({ tracks: this.state.tracks.concat(tracks)});


    }).catch((err)=>{
        console.log("There has been an error");
    });

  }

   focus() {
   this.textInput.focus();
 }


    keyPress(e){
       if(e.keyCode == 13){
          console.log('value', e.target.value);
          // put the login here
       }
    }    


render() {   


  const {term, data, tracks} = this.state;

  const loader = <div className="loader2"> </div>;

  var items = [];
  const imageUrl = require(`../assets/Book.jpg`)

  tracks.filter(searchingFor(term)).map(function(title, i)
{
    items.push(
            <div>
              <MuiThemeProvider>
                <Paper style={{ borderRadius: "2em",
                  background: '#ffffff'
                }} zDepth={1} >

          <ItemViewAll
            key={title.id}
              />
      </Paper>
      </MuiThemeProvider>
      </div>
    );
  }, this);



    return (
      <div>    

            <Fade in={true}  timeout={1000}>

<div >

  <MuiThemeProvider>

    <TextField hintText='Bot suchen...'

         type="Text"
         onChange={this.searchHandler}
         value={term}
         underlineFocusStyle={{borderColor: '#B00020', borderWidth: 3}}
         underlineStyle={{borderColor: '#B00020', borderWidth: 1.5, top: '45px'}}
         hintStyle={{fontSize: '8.1vw', fontFamily: 'Anton', color: 'rgba(255,255,255,0.9)'}}
         inputStyle={{fontSize: '8.1vw', fontFamily: 'Anton', color: '#ffffff'}}
         ref={(input) => { this.textInput = input; }}
         style={{caretColor: '#ffffff', width: '90%', maginLeft: 'auto', marginRight: 'auto', marginTop: '12%' }}
         InputLabelProps={{ shrink: true }}
         />


     </MuiThemeProvider>
      </div>
      </Fade>   



    <InfiniteScroll
       pageStart={1}
       loadMore={this.loadContent.bind(this)}
       hasMore={this.state.hasMoreItems}
       initialLoad={true}

      >


              {items}
         </InfiniteScroll>    


</div>
    )
  }
}

export default ViewAll;
const{scaleDown}=transitions;
函数搜索(术语){
返回函数(x){
返回x.title.toLowerCase().includes(term.toLowerCase())||
x、 body.toLowerCase()。包括(term.toLowerCase());
}
}  
类ViewAll扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
术语:“”,
对,,
轨道:[],
hasMoreItems:是的,
页码:2,
}
this.searchHandler=this.searchHandler.bind(this);
this.focus=this.focus.bind(this);
this.keyPress=this.keyPress.bind(this);
}
loadContent(){
var requestUrl=this.props.url;
获取(requestUrl+this.state.page+'&_limit=3')。然后((响应)=>{
返回response.json();
})。然后((曲目)=>{
this.setState({tracks:this.state.tracks.concat(tracks)});
this.setState({page:this.state.page+1});
if(this.state.page==6){
this.setState({hasMoreItems:false})
}
}).catch((错误)=>{
log(“出现错误”);
});
}
componentDidMount(){
滚动到(0,0);
var requestUrl=this.props.url;
获取(请求URL+'1&_limit=3')
。然后((响应)=>{
返回response.json();
})。然后((数据)=>{
this.setState({tracks:data});
})
.catch((错误)=>{
log(“出现错误”);
});
//这是focus();
}
searchHandler(事件){
this.setState({term:event.target.value});
var requestUrl=https://questdb.herokuapp.com/all?q='
获取(requestUrl+this.state.term)。然后((响应)=>{
返回response.json();
})。然后((曲目)=>{
this.setState({tracks:this.state.tracks.concat(tracks)});
}).catch((错误)=>{
log(“出现错误”);
});
}
焦点(){
this.textInput.focus();
}
按键(e){
如果(e.keyCode==13){
console.log('value',例如target.value);
//把登录名放在这里
}
}    
render(){
const{term,data,tracks}=this.state;
常量加载器=;
var项目=[];
const imageUrl=require(`../assets/Book.jpg`)
tracks.filter(搜索(术语)).map(函数(标题,i)
{
推(
);
},这个);
返回(
{this.textInput=input;}}
样式={{caretColor:'#ffffff',宽度:'90%,maginLeft:'auto',marginRight:'auto',marginTop:'12%}
InputLabelProps={{shrink:true}
/>
{items}
)
}
}
导出默认的ViewAll;
在这里,您可以使用已损坏的搜索功能查看网站。正如您所看到的,项目显示为两倍甚至三倍…文本字段清空后,搜索结果应被删除,仅显示正常获取的结果

(使用chrome中的移动版本)


谢谢:)

使用lodash debounce。它用于这个确切的用例

https://stackoverflow.com/questions/48046061/using-lodash-debounce-in-react-to-prevent-requesting-data-as-long-as-the-user-is
样本:

import React, {Component} from 'react'
import { debounce } from 'lodash'

class TableSearch extends Component {

  //********************************************/

  constructor(props){
    super(props)

    this.state = {
        value: props.value
    }

    this.changeSearch = debounce(this.props.changeSearch, 250)
  }

  //********************************************/

  handleChange = (e) => {
    const val = e.target.value

    this.setState({ value: val }, () => {
      this.changeSearch(val)
    })
  }

  //********************************************/

  render() {

    return (
        <input
            onChange = {this.handleChange}
            value = {this.props.value}
        />
    )
  }

  //********************************************/

}
import React,{Component}来自“React”
从“lodash”导入{debounce}
类表搜索扩展组件{
//********************************************/
建造师(道具){
超级(道具)
此.state={
价值:道具价值
}
this.changeSearch=debounce(this.props.changeSearch,250)
}
//********************************************/
handleChange=(e)=>{
const val=e.target.value
this.setState({value:val},()=>{
此.changeSearch(val)
})
}
//********************************************/
render(){
返回(
)
}
//********************************************/
}

使用lodash去盎司。它用于这个确切的用例

https://stackoverflow.com/questions/48046061/using-lodash-debounce-in-react-to-prevent-requesting-data-as-long-as-the-user-is
样本:

import React, {Component} from 'react'
import { debounce } from 'lodash'

class TableSearch extends Component {

  //********************************************/

  constructor(props){
    super(props)

    this.state = {
        value: props.value
    }

    this.changeSearch = debounce(this.props.changeSearch, 250)
  }

  //********************************************/

  handleChange = (e) => {
    const val = e.target.value

    this.setState({ value: val }, () => {
      this.changeSearch(val)
    })
  }

  //********************************************/

  render() {

    return (
        <input
            onChange = {this.handleChange}
            value = {this.props.value}
        />
    )
  }

  //********************************************/

}
import React,{Component}来自“React”
从“lodash”导入{debounce}
类表搜索扩展组件{
//********************************************/
建造师(道具){
超级(道具)
此.state={
价值:道具价值
}
this.changeSearch=debounce(this.props.changeSearch,250)
}
//********************************************/
handleChange=(e)=>{
const val=e.target.value
this.setState({value:val},()=>{
此.changeSearch(val)
})
}
//********************************************/
render(){
返回(
)
}
//********************************************/
}

如果您不需要完整的lodash软件包,您可以自己编写:

function debounce(f, ms) {

  let timer = null;

  return function (...args) {
    const onComplete = () => {
      f.apply(this, args);
      timer = null;
    }

    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(onComplete, ms);
  };
}
第一个参数(f)是您的函数,不应比 第二个参数(毫秒)-毫秒数。因此,在您的情况下,您可以用下一种方式编写处理程序:

handleChange = debounce((e) => {
  const val = e.target.value

  this.setState({ value: val }, () => {
    this.changeSearch(val)
  })
}, 1000) // second arg (1000) is your amount of ms

如果您不需要完整的lodash软件包,您可以自己编写:

function debounce(f, ms) {

  let timer = null;

  return function (...args) {
    const onComplete = () => {
      f.apply(this, args);
      timer = null;
    }

    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(onComplete, ms);
  };
}
第一个参数(f)是您的函数,不应比 第二个参数(毫秒)-毫秒数。因此,在您的情况下,您可以用下一种方式编写处理程序:

handleChange = debounce((e) => {
  const val = e.target.value

  this.setState({ value: val }, () => {
    this.changeSearch(val)
  })
}, 1000) // second arg (1000) is your amount of ms

使用onChange时使用lodash debounce,以便在输入更改时调用该事件。预期的行为是什么?使用onChange时使用lodash debounce,因此在输入更改时调用事件。预期行为是什么?虽然这在理论上可以回答问题,但在此处包括答案的基本部分并提供示例,并提供链接供参考。虽然这在理论上可以回答问题,但在此处包括答案的基本部分并提供示例,并提供链接供参考。