我有一个React-Redux thunk动作,它从API服务器检索类别,然后将它们添加到Redux存储中:
(categoryActions.js)
export const fetchCategories = () => dispatch => (
CategoryAPI.getCategories().then(categories => {
for(const category of categories) {
const {name, path} = category
dispatch(addNewCategory(name,path))
}
})
)
使用以下API调用时,它可以正常工作:
(categoryApi.js)
const apiServerURL = "http://localhost:3001"
const headers = {
'Content-Type': 'application/json',
'Authorization': 'whatever-you-want'
}
export const getCategories = () => (
fetch(`${apiServerURL}/categories`, { headers })
.then(res => res.json())
.then(data => data.categories)
)
但是,当我尝试在不同的文件中定义API常量时,如下所示:
(apiConstants.js)
export const HEADERS = {
'Content-Type': 'application/json',
'Authorization': 'whatever-you-want'
}
export const SERVER_URL = "http://localhost:3001"
然后在categoryApi.js中使用它们:
import {
HEADERS,
SERVER_URL
} from './apiConstants'
export const getCategories = () => (
fetch(`${SERVER_URL}/categories`, { HEADERS })
.then(res => res.json())
.then(data => data.categories)
)
我从上面categoryActions.js中的thunk动作的第3行收到以下错误:
未处理的拒绝(TypeError):无法读取属性 “未定义的符号(Symbol.iterator)”
有什么问题?
答案 0 :(得分:2)
问题是你的变量是大写的,所以你需要正确设置属性,因为fetch
期望它是小写的:
export const getCategories = () => (
fetch(`${SERVER_URL}/categories`, { headers: HEADERS })
.then(res => res.json())
.then(data => data.categories)
)
-
{ headers }
相当于:
{ headers: headers }
所以在你的第二个例子中,你把它大写了:
{ HEADERS: HEADERS }