如何通过Redux Thunk本地读取customData.json数据?
问题
我希望通过下方代码读取customData.json中的数据,但当前fetch方法需要传入URL,而我想本地读取该文件,请问是否可行?代码如下:
var customData = require('./customData.json'); export function fetchQuestions() { return dispatch => { fetch(customData, { method: 'get', headers: { 'Accept': 'application/json', "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" } }) .then(payload => payload.json()) .then(payload => payload.results) .then(payload => dispatch({ type: 'FETCH_QUESTIONS', payload: payload }) ) } }
回答
当然可行,但你现在的写法有点绕路了——你已经用require('./customData.json')把本地JSON文件直接解析成JavaScript对象了,完全没必要再用fetch去请求它呀!
给你两种更合理的处理方式:
方式一:直接使用已导入的JSON数据
既然customData已经是解析好的对象,你可以直接提取需要的results字段传给dispatch,省去fetch的冗余步骤:
var customData = require('./customData.json'); export function fetchQuestions() { return dispatch => { const payload = customData.results; dispatch({ type: 'FETCH_QUESTIONS', payload: payload }); }; }
方式二:如果一定要用fetch读取本地文件
如果你坚持想用fetch(比如后续计划改成远程API请求),那得把customData.json放到项目的静态资源目录里(比如React的public文件夹、Vue的public/static文件夹),然后用文件的相对URL作为fetch的参数,而不是导入的对象:
export function fetchQuestions() { return dispatch => { fetch('./customData.json', { method: 'get', headers: { 'Accept': 'application/json' // GET请求不需要设置Content-Type,因为没有请求体需要描述 } }) .then(response => response.json()) .then(data => data.results) .then(payload => dispatch({ type: 'FETCH_QUESTIONS', payload: payload })) .catch(error => console.error('读取本地JSON失败:', error)); }; }
这种方式下,浏览器会通过HTTP请求加载静态资源目录里的JSON文件,你不需要用require提前导入。另外注意去掉多余的Content-type头,GET请求用不上这个。
内容的提问来源于stack exchange,提问作者Chris Henry
相关产品推荐
相关产品推荐

