reactjs - 再次使用搜索和渲染组件
问题描述
我想要一个搜索框,搜索后,我从 API 和setState
. ComponentDidMount
我在搜索后发送我的请求,ComponentDidMount
不要打电话。如果我使用componentDidupdate
我有永远不会完成的 for 循环。我该怎么办?
async componentDidMount() {
console.log('componentDidMount');
try {
const response = await axios.get(`http://api.tvmaze.com/search/shows?q=${this.state.searchString}`);
console.log(response.data);
this.setState({ movies: response.data });
}catch (error) {
console.log(error);
}
}
和 :
constructor(props) {
super(props);
this.state = {
movies: [],
searchString: 'bing bang',
boolian: true,
};
}
async componentDidUpdate() {
console.log('componentDidUpdate');
const { navigation } = this.props;
const searchString = navigation.getParam('searchString', 'searchString');
if (this.state.boolian) {
this.setState({ boolian: false, searchString });
}
}
解决方案
您应该将您的 api 调用分离到另一个方法并在搜索时调用它
constructor(props) {
super(props);
this.state = {
movies: [],
searchString: 'bing bang',
boolian: true,
};
}
showSearch = async (searchString) => {
try {
const response = await axios.get(`http://api.tvmaze.com/search/shows?q=${searchString}`);
this.setState({ movies: response.data });
} catch (error) {
console.log(error);
}
}
async componentDidMount() {
this.showSearch(this.state.searchString)
}
并在搜索按钮上按下您可以调用this.showSearch(searchString)
推荐阅读
- python - python:使用字段分隔符打印单列
- php - 如何在 Symfony 中使用“IntlDateFormatter”?
- javascript - UBUNTU、NODE-GYP、CANVAS- 获取构建错误
- regex - 如何使用 Ansible 使用正则表达式将文件从本地复制到远程?
- reinforced-typings - 如何将类型(按组)指向不同的类和/或命名空间?
- scala - java.lang.AssertionError:断言失败
- css - 如何设计风格带有缺口底部的矩形和纯 CSS?
- python - 使用 Pandas 转换时值错误不匹配
- c - MISRAC2012-Rule-18.1_d 以太网 MAC 问题
- php - 如何在 Woocommerce 中显示当前应用的优惠券 slug?