我如何使用“ componentDidMount”来“获取”并传递查询字符串

时间:2019-09-18 14:49:31

标签: reactjs redux

我创建了一个gif搜索引擎,在搜索字段中键入它会显示与该文本相关的“ gifs”,我使用了“ superagent”来处理api,并且使用了此代码

  onSearchChange = (event) => {
    const url = `http://api.giphy.com/v1/gifs/search?q=${event.target.value.replace(/\s/g, '+')}&limit=10&api_key=${API_KEY}`;
      request.get(url, (err, res) => {
        this.setState({ gifs: res.body.data })
      });
  }

现在我的问题是如何将“ componentDidMount”与“ fetch”一起使用以更改“ onSearchChange”

1 个答案:

答案 0 :(得分:0)

我认为您希望每次search字段更新时都调用api。在这种情况下,进行api调用的适当生命周期方法为componentDidUpdatecomponentDidMount仅在安装组件后才会调用。

1。更改search字段后,更新state以反映当前的search字段。    例如this.setState({ search: currentValue })

2。状态一旦更新,将调用componentDidUpdate。现在,您可以使用此方法进行api调用。

componentDidUpdate(prevProps, prevState) {
      if (prevState.search !== this.state.search) { // or compare with `prevState`
        this.onSearchChange(this.state.search);
      }
    }