我想要一个搜索框,搜索后,我从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 });
}
}
答案 0 :(得分:2)
您应将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)