在获取json API中搜索

时间:2018-07-28 11:20:53

标签: reactjs api ecmascript-6 fetch

我终于使用React通过React从API获取数据并在控制台中获取了JSON。现在,我还有另一个挑战。

我有一个搜索组件,我想搜索得到的JSON并在屏幕上显示结果。我该怎么办?

这是我到目前为止写的:

class Global extends Component {
  constructor(props) {
    super(props);
    this.state = {
      query: "",
      items: []
    };
  }
  search() {
    let url = "/*my url*/";

    fetch(url, {
      method: "GET", // *GET, POST, PUT, DELETE, etc.
      mode: "cors", // no-cors, cors, *same-origin
      cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
      credentials: "same-origin", // include, same-origin, *omit
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json; charset=utf-8",
        Authorization: "Bearer /*my key*/",
        "Access-Control-Allow-Headers": "accept"
      }
      // redirect: "follow", // manual, *follow, error
      // referrer: "no-referrer", // no-referrer, *client
      // body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
      .then(response => response.json())
      .then(json => console.log(json));
  }

  render() {
    return (
      <div className="global">
        <h2>book Explore!</h2>
        <FormGroup>
          <InputGroup>
            <FormControl
              type="text"
              placeholder="Search for a Branches"
              onChange={event => this.setState({ query: event.target.value })}
              onKeyPress={event => {
                if (event.key === "Enter") {
                  this.search();
                }
              }}
            />
            <InputGroup.Addon onClick={() => this.search()}>
              <Glyphicon glyph="search" />
            </InputGroup.Addon>
          </InputGroup>
          <Gallery items={this.state.items} />
        </FormGroup>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

第一件事是将搜索功能绑定到construcor块中,如下所示:

  constructor(props) {
    super(props);
    this.state = {
      query: "",
      items: []
    };
    this.search = this.search.bind(this);
  }

似乎您的代码<Gallery />块取决于this.state.items的值,在获取搜索调用后获得响应后,便使用items将所需对象分配为setState状态功能如下所示(第二个then块):

search() {
    let url = "/*my url*/";

    fetch(url, {
      method: "GET", // *GET, POST, PUT, DELETE, etc.
      mode: "cors", // no-cors, cors, *same-origin
      cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
      credentials: "same-origin", // include, same-origin, *omit
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json; charset=utf-8",
        Authorization: "Bearer /*my key*/",
        "Access-Control-Allow-Headers": "accept"
      }

    })
      .then(response => response.json())
      .then(json => this.setState({items=json}));
  }