【问题标题】:when I type story in my textbox it should hit this api当我在我的文本框中输入故事时,它应该点击这个 api
【发布时间】:2020-02-04 06:04:53
【问题描述】:
  • 当我在文本框中输入故事时,它应该会点击这个 api https://hn.algolia.com/api/v1/search?tags=story
  • 数据应显示在浏览器中。
  • 但现在没有通话。
  • 所有相关代码都在 searchbar.js 中
  • 你能告诉我如何解决它吗?
  • 在下面提供我的代码 sn-p 和沙箱。

https://codesandbox.io/s/adoring-swanson-ioy2u

class SearchBar extends Component {
  async searchByKeyword({ target }) {
    await this.getQuery("story", target.value);
  }

  async componentDidMount() {
    await this.getQuery("story", "butts");
  }

  getQuery = async (type = "", search_tag = "") => {
    var url = "https://hn.algolia.com/api/v1/search?tags=";
    const resp = await fetch(`${url}${type}&query=${search_tag}`);
    return resp.json();
  };

  render() {
    return <input type="text" onChange={this.searchByKeyword} />;
  }
}

【问题讨论】:

  • 您从不使用收到的数据设置状态或尝试渲染任何数据
  • 嘿,你能更新沙箱里的代码吗,太混乱了:(
  • 我只是偏离了我在问题中看到的内容。甚至没有看过沙盒。上面的代码对等待结果没有任何作用

标签: javascript html reactjs api redux


【解决方案1】:

我已更新your sandbox

您的 searchByKeyword 方法未绑定到 SearchBar 组件,这导致 this 在方法内未定义。通过添加此代码可以正常工作:

constructor(props) {
    super(props);

    this.searchByKeyword = this.searchByKeyword.bind(this);
}

每次获取数据时,您的数据都会发送到SearchBar 组件的onFetch 属性。 此数据由您的 App 组件处理:

<SearchBar onFetch={this.onFetch} />

其中数据设置为状态。该状态在搜索输入下方表示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    相关资源
    最近更新 更多