- 当我在我的文本框中输入故事时,它应该点击这个 api https://hn.algolia.com/api/v1/search?tags=story
- 数据应显示在浏览器中。
- 但现在没有通话。
- 所有相关代码都在 searchbar.js 中
- 你能告诉我如何解决吗?
- 在下面提供我的代码片段和沙箱。
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} />;
}
}
最佳答案
我已经更新了 your sandbox .
您的 searchByKeyword
方法未绑定(bind)到 SearchBar
组件,这导致 this
在方法内部未定义。通过添加此代码可以正常工作:
constructor(props) {
super(props);
this.searchByKeyword = this.searchByKeyword.bind(this);
}
每次获取数据时,您的数据都会发送到 SearchBar
组件的 onFetch
属性。
此数据由您的 App
组件处理:
<SearchBar onFetch={this.onFetch} />
其中数据设置为状态。该状态显示在搜索输入下方。
关于javascript - 当我在我的文本框中输入故事时,它应该点击这个 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261154/