未处理拒绝进口字符串常量时,而不是宣布他们在本地

问题描述:

我有一个阵营 - 终极版咚,从一个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行得到以下错误:

Unha ndled Rejection(TypeError):无法读取属性 'Symbol(Symbol.iterator)'的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