首页 > 解决方案 > 再次使用搜索和渲染组件

问题描述

我想要一个搜索框,搜索后,我从 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 });
    }
  }

标签: reactjsreact-native

解决方案


您应该将您的 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)


推荐阅读