js容错处理
# 优化技巧
# 常用方式
// response 是来自接口的数据
const response = {
code: 200,
msg: 'message',
data: {
total: 100,
page: 1,
pageSize: 10,
content: []
}
}
const goodsList = response.data.content.forEach(() => {})
const total = response.data.total
// or
const goodsList = response.data && response.data.content && response.data.content.forEach(() => {})
const total = response.data && response.data.total
# 优化方式
提示
只需要简单的两个处理,一个是解构,一个是给默认值
const { data = {} } = response
const { content = [], total = []} = data
# 异常情况
因此我们得保证拿到的数据不能存在null,不然上面的代码就没意义了。
const response = {
data :null
}
可以放在中间层做个数据处理
上次更新: 2021/12/19, 18:05:42