代码之家  ›  专栏  ›  技术社区  ›  eureka

再次使用搜索和渲染组件

  •  1
  • eureka  · 技术社区  · 6 年前

    我想有一个搜索框,搜索后,我要求并获得数据从API和 setState . ComponentDidMount 经过搜查, componentDidupdate 我有一个从未完成的循环。我该怎么办?

      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 });
        }
      }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Pritish Vaidya    6 年前

    您应该分离对另一个方法的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)