我按照以下链接尝试做一个 poc https://www.reddit.com/r/reactjs/comments/82mxz3/how_to_make_an_api_call_on_props_change在 Searchbar 中,我创建了一个文本框,当我提供 componentWillRecieveProps 并打印值以将其传递给 api 但没有打印时,我正在获取值但在 index.js 中。你能告诉我如何修复它吗?在下面提供更新的代码沙箱和代码片段。https://codesandbox.io/s/eloquent-galielo-14874//import React from "react";import ReactDOM from "react-dom";import React, { Fragment, useState, Component } from "react";import "./styles.css";class SearchBar extends Component { state = { groupCheckBoxValues: [], groupRadioValue: "PRO" }; getInitialState() { return { value: "Hello!" }; } handleChange(event) { console.log("handleChange", event.target.value); this.setState({ value: event.target.value }); } componentWillReceiveProps({ search }) { console.log(search); } componentDidMount() { this.fetchdata("story"); } fetchdata(type = "", search_tag = "") { var url = "https://hn.algolia.com/api/v1/search?tags="; fetch(`${url}${type}&query=${search_tag}`) .then(res => res.json()) .then(data => { this.props.getData(data.hits); }); } render() { return ( <input type="text" value={this.state.value} onChange={this.handleChange} /> ); }}export default SearchBar;
1 回答
弑天下
TA贡献1818条经验 获得超8个赞
您实际上并未将文本输入的值传递给提取请求。
我推荐这样的东西:
class SearchBar extends Component {
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}
/>
);
}
}
我删除了状态和事物,因为它似乎与问题并不完全相关。
添加回答
举报
0/150
提交
取消