react-native - 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 ()
}
}
当我运行项目时,终端显示check1
但check2
没有显示
解决方案
您需要将代码的最后部分放入一个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
因为您不重新分配它们(也不应该!),并将它们仅移动到所需的范围内。
推荐阅读
- python - Keras ModelCheckpoint 不在 Windows 上保存任何文件
- javascript - Angular Firebase - 从存储中下载文件
- php - 你如何计算下面数组中存在的单词数?
- malloc - 常量缓冲区的alignas_malloc() vs alignas()
- json - 我正在尝试在 React js 中对本地 json 文件进行排序,但出现错误:“TypeError:_Data_place_json__WEBPACK_IMPORTED_MODULE_1__ 不可迭代。”
- mysql - 在 mysql [42000] [1064] 中创建函数错误
- html - 一切都在不断移动到底部
- javascript - Puppeteer 错误,在抓取白页时无法读取未定义的属性“getProperty”
- node.js - Express 服务器返回文件而不是 HTML 页面
- docker - 如何连接到 docker 容器中的交互式进程