gpt4 book ai didi

javascript - 导入字符串常量而不是在本地声明它们时出现未处理的拒绝

转载 作者:行者123 更新时间:2023-11-29 21:00:25 25 4
gpt4 key购买 nike

我有一个 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 行得到以下错误:

Unhandled Rejection (TypeError): Cannot read property 'Symbol(Symbol.iterator)' of undefined

有什么问题?

最佳答案

问题是你的变量是大写的,所以你需要正确设置属性,因为 fetch 期望它是小写的:

export const getCategories = () => (
fetch(`${SERVER_URL}/categories`, { headers: HEADERS })
.then(res => res.json())
.then(data => data.categories)
)

--

{ headers }

相当于:

{ headers: headers }

所以在你的第二个例子中你把它大写了:

{ HEADERS: HEADERS }

这被称为 property shorthand

关于javascript - 导入字符串常量而不是在本地声明它们时出现未处理的拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46781525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com