将React组件重新渲染回原始状态

时间:2018-11-23 06:38:45

标签: javascript reactjs ecmascript-6

我有这个组件,它在axios get请求上返回一堆li,用户输入文本并且搜索被更新。我希望React在searchInput为null时重新呈现该组件,基本上返回其原始状态

  class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      searchResults: [], // API Call returns an array of results
      searchInput: '', // Search Term for API Call
            searchImage: [] //base_url, a file_size and a file_path.
    }
  }


performSearch = () => { // Requesting data from API
    axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
        .then((res) => {
            console.log(res.data.results);
            this.setState({ searchResults: res.data.results});
        });
}

以下是触发渲染的功能

   handleInputChange = () => {
        this.setState({
            searchInput: this.search.value // User input
        }, () => {
            if (this.state.searchInput && this.state.searchInput.length >1 ) {
                if (this.state.searchInput.length % 2 === 0) { // Request data on user input
                    this.performSearch();
                } else if (this.state.searchInput && this.state.searchInput.length === 0 ) {
                    return ({ searchResults: null}) 
                }
            }
        });
    }




import React from 'react'

const Suggestions = (props) => {
  const options = props.searchResults.map(r => (
    <li
      key={r.id} >
      <img src={`https://image.tmdb.org/t/p/w185/${r.poster_path}`} alt={r.title} />
      <a href='#t' className='rating'><i className='fas fa-star fa-fw' />{r.vote_average}</a>
    </li>
  ))
  return <ul className='search-results'>{options}</ul>
}

export default Suggestions

目前的问题是,如果我搜索某些内容(例如“权力游戏”),则会呈现li的内容,但是如果我将其清除为空字符串,则仍然会遗留li的内容...我不知道想看什么,如果searchInput为空

编辑:performSearch在清除searchInput时再次被触发,并返回最后两个字符,这使我剩下了li的

1 个答案:

答案 0 :(得分:1)

您尚未处理handleInputChange方法中正确的条件。如果外部条件失败,内部将永远不会执行

 handleInputChange = () => {
    this.setState({
        searchInput: this.search.value // User input
    }, () => {
        if (this.state.searchInput && this.state.searchInput.length >1 ) {
            if (this.state.searchInput.length % 2 === 0) { // Request data on user input
                this.performSearch();
            }
        } else {
             this.now = Date.now();
             this.setState({ searchResults: []}) 
        }
    });
}

此外,这里的问题可能是API调用的竞争条件。可能发生的情况是,尽管您将setState设置为null或empty却清除了输入,然后API响应,再次设置了状态。最好的处理方式是仅接受与上次请求相对应的响应

performSearch = () => { // Requesting data from API
    let now = (this.now = Date.now());
    axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
        .then((res) => {
            console.log(res.data.results);
            // Accepting response if this request was the last request made
            if (now === this.now) {
               this.setState({ searchResults: res.data.results});
            }
        });
}