reactjs - 反应:未处理的拒绝(TypeError):无法读取未定义的属性'catch'
问题描述
我正在尝试获取带有 axios 的表单列表进行反应
这是功能
useEffect(() => {
const fetchData = async () => {
dispatch({ type: 'SET_STATE', payload: { loading: true } })
const response = await axios
.get(`${API_URL}/form`, {
userId: localStorage.getItem('userId'),
headers: {
authorization: localStorage.getItem('userId')
}
})
console.log(response)
.catch((err) => {
if (err.response.status === 401) history.push('/login')
return dispatch({
type: 'SET_STATE',
payload: { loading: false, error: err.response.data.msg }
})
})
dispatch({
type: 'SET_STATE', payload: {
data: response.data.form,
loading: false,
},
})
}
fetchData()
return () => {
dispatch({ type: 'SET_STATE', payload: { loading: true, error: '' } })
}
}, [])
这是减速机
const initialState = {
data: [],
loading: false,
error: '',
}
const formReducer = (state = initialState, action) => {
switch (action.type) {
case 'SET_STATE':
return { ...state, ...action.payload }
default:
return state
}
}
但我收到此错误:
未处理的拒绝(TypeError):无法读取未定义的属性“catch”
解决方案
console.log
您通过添加betweenget
和打破了承诺链catch
。使用console.log
inthen
代替,如下所示:
另外,您正在将 with 混合async/await
在一起then
。虽然,它response
不会像你期望的那样工作。只需使用then
链接。
useEffect(() => {
const fetchData = () => {
dispatch({ type: 'SET_STATE', payload: { loading: true } })
axios
.get(`${API_URL}/form`, {
...
})
// add the console in then
.then(response=>{
console.log(response))
dispatch({
type: 'SET_STATE',
payload: {
data: response.data.form,
loading: false,
}
})
})
.catch((err) => {
...
})
}
fetchData()
return () => {
dispatch({ type: 'SET_STATE', payload: { loading: true, error: '' } })
}
}, [])
推荐阅读
- asp.net-core - 通过 LDAP 使用 ASP.NET Core 针对 Active Directory 登录身份验证时出错
- c# - 使用后处理效果保存来自 Unity 相机的图像
- php - 我的 PHP 代码中有一个简单的表单,数据不会传递到 nesxt 页面
- javascript - CTRL + C 和关键字键 C ,两个事件同时工作 JavaScript || jQuery
- ssh - 有没有办法使用来自 libssh 的 ~/.ssh/config 的配置值?
- r - 按日期对表进行分组,然后对 R 中的值和计数求和
- c# - 在.net核心中绑定原始请求体而不读取请求流
- java - 是否可以在 NetBeans IDE 输出屏幕中删除/隐藏多余的行?如果可能,那怎么办?
- kotlin - `class C(val field: T): T by field` 是什么意思?
- android - photoshop text 和 android textview 有什么区别?