React.js搜索栏始终提取相同的内容

时间:2018-02-06 14:31:28

标签: javascript reactjs fetch-api

我正在使用React.js构建搜索引擎,在那里我可以使用他们的API查找GIPHY gif。每当我输入一个单词(任何单词)时,它总是加载相同的GIF,当我擦除并写下另一个单词时,GIF不会更新。

index.js:

import React from 'react'; //react library
import ReactDOM from 'react-dom'; //react DOM - to manipulate elements
import './index.css';
import SearchBar from './components/Search';
import GifList from './components/SelectedList';

class Root extends React.Component { //Component that will serve as the parent for the rest of the application.

constructor() {
    super();

    this.state = {
        gifs: []
    }
    this.handleTermChange = this.handleTermChange.bind(this)
}

handleTermChange(term) {
    console.log(term);
    let url = 'http://api.giphy.com/v1/gifs/search?q=${term.replace(/\s/g, '+')}&api_key=aOfWv08Of7UqS6nBOzsO36NDvwYzO6io';
        fetch(url).
    then(response => response.json()).then((gifs) => {
        console.log(gifs);
        this.setState({
            gifs: gifs
        });
    });
};  


render() {
    return (
      <div>
        <SearchBar onTermChange={this.handleTermChange} />
        <GifList gifs={this.state.gifs} />
      </div>
    );
}
}

ReactDOM.render( <Root />, document.getElementById('root'));

search.js

import React, { PropTypes } from 'react'

import './Search.css'

class SearchBar extends React.Component {
onInputChange(term) {
    this.props.onTermChange(term);
}

render() {
    return (
        <div className="search">
            <input placeholder="Enter text to search for gifs!" onChange={event => this.onInputChange(event.target.value)} />
        </div>
    );
}
}

export default SearchBar;

Giflist:

import React from 'react';
import GifItem from './SelectedListItem';

const GifList = (props) => {
console.log(props.gifs);
  const gifItems = props.gifs && props.gifs.data && props.gifs.data.map((image) => { 
    return <GifItem key={image.id} gif={image} />
});

  return (
 <div className="gif-list">{gifItems}</div>
  );
};

export default GifList;

GifItem:

import React from 'react';

const GifItem = (image) => {
  return (
<div className="gif-item">
  <img src={image.gif.images.downsized.url} />
</div>
  )
};

export default GifItem;

我似乎无法在这里找到问题所在。是因为this.handleTermChange = this.handleTermChange.bind(this)还是没有&#34;更新&#34;国家之后?

欢迎任何帮助:)谢谢!

1 个答案:

答案 0 :(得分:3)

这是因为,你没有将用户输入的术语值放在网址中,所有时间都是用静态值term命中api,在这里:

'http://api.giphy.com/v1/gifs/search?q=${term.replace(/\s/g, '+')}&api_key=aOfWv08Of7UqS6nBOzsO36NDvwYzO6io';

'替换为&#39; (勾),像这样:

let url = `http://api.giphy.com/v1/gifs/search?q=${term.replace(/\s/g, '+')}&api_key=aOfWv08Of7UqS6nBOzsO36NDvwYzO6io`;

查看MDN文档,了解有关 Template Literals 的详细信息。