首页 > 解决方案 > React Native ComponentDidMount 未加载

问题描述

由于某种原因,我的 React Native 项目中的ComponentDidMount函数似乎没有运行。最近我尝试在我的代码中添加一个搜索功能,在我实现了这些功能之后,该功能似乎无法正常工作。所以我试图删除新功能,但该功能仍然没有运行。

这是代码,也许我错过了一些东西。

export default class CategoryScreen extends React.Component {

  constructor(props){
    super(props);
    this.navigate = this.props.navigation.navigate;
        this.state={
      data : [],
      isVisible: true,
      city : '280',
      isLoading: true,
      searched: ''
    }
  }
async componentDidMount() {
    let id = this.props.navigation.state.params.category
    let city = this.state.city
    let result;
    try {
        console.log('check1')
      result = await axios.request({
        method: 'get',
        url: `https://developers.zomato.com/api/v2.1/search?city_id=${city}&q=${searched}&category=${id}`,
        headers: {
          'Content-Type': 'application/json',
          'user-key': "a31bd76da32396a27b6906bf0ca707a2",
        },
      })
    } catch (err) {
      err => console.log(err)
    }
    this.setState({
      isLoading: false,
      data: result.data.restaurants
    })
    console.log('check2')
  }
render() {
    return ()
}
}

当我运行项目时,终端显示check1check2没有显示

标签: react-native

解决方案


您需要将代码的最后部分放入一个finally {...}块中,该块将在try成功完成后执行,或者 - 如果触发了 catch -catch块完成。

需要注意的一件事:因为你没有初始值result,如果你的 try 块抛出一个错误,那么当你尝试使用 setState 时你会得到另一个result.data.restaurants错误,因为data不存在。

我认为解决这个问题的最干净的方法是将 setState 一分为二。仅data当您有结果时才设置:

async componentDidMount() {
  try {
    const id = this.props.navigation.state.params.category;
    const city = this.state.city;

    console.log('check1');

    const result = await axios.request({
      method: 'get',
      url: `https://developers.zomato.com/api/v2.1/search?city_id=${city}&q=${searched}&category=${id}`,
      headers: {
        'Content-Type': 'application/json',
        'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
      }
    });

    this.setState({ data: result.data.restaurants }); // only triggers if your axios request worked
  } catch (err) {
    console.log(err); // remove the erroneous `err =>`
  } finally {
    // add this finally block
    this.setState({ isLoading: false }); // now only set isLoading once everything is complete
    console.log('check2');
  }
}

请注意,还将您的let声明更改为,const因为您不重新分配它们(也不应该!),并将它们仅移动到所需的范围内。


推荐阅读