我点击了下面的链接,并试图进行poc https://www.reddit.com/r/reactjs/comments/82mxz3/how_to_make_an_api_call_on_props_change
在搜索栏中,我创建了一个文本框,当我给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;
您实际上没有将文本输入的值传递给获取请求。
阅读本文并尝试正确获取。