【发布时间】:2019-02-12 17:20:45
【问题描述】:
我在从 URL 获取数据时遇到问题。 当我在文件中写入数据时,应用程序运行良好,但是当我尝试从 URL 调用相同的数据时,我得到了错误。
我使用小型应用程序进行了测试,其中所有内容都在 App.js 文件中,并且可以正常工作。但是新应用程序有点分为多个文件,这就是问题的开始。
这是我调用数据和代码工作的 events.js:
import {
TOGGLE_FAVORITE_EVENT
} from '../const';
import toggle from './toggle';
let data = [
{
type: 'PARTY',
title: 'Party in the Club',
adress: 'New York',
date: '9. 9. 2019.',
image: '',
text: [
'Party description...'
],
coordinates: [50, 50],
id: 'events_1'
}
];
let events = (state = data, action) => {
switch(action.type){
case TOGGLE_FAVORITE_EVENT:
return toggle(state, action.payload.id);
default:
return state;
}
}
export default events;
这是我尝试获取数据的方式,但不起作用:
import {
TOGGLE_FAVORITE_EVENT
} from '../const';
import toggle from './toggle';
// WP REST API
const REQUEST_URL = 'http://some-url.com/test.json';
let data = fetch(REQUEST_URL)
.then(response => response.json() )
.then(data => console.log(data) )
.catch(error => console.log(error));
let events = (state = data, action) => {
switch(action.type){
case TOGGLE_FAVORITE_EVENT:
return toggle(state, action.payload.id);
default:
return state;
}
}
export default events;
注意:.json 文件应该没问题,因为它适用于小应用程序。
【问题讨论】:
-
您在开发工具的控制台上看到任何错误吗?还有cors错误吗?该网址与您的应用程序托管在同一主机上?
-
我认为您正在尝试使用从 URL 加载的 json 文件的内容来初始化状态:如果我是您,我会专门创建一个操作来执行此操作。你需要一个库来处理异步进程,比如 redux-thunk 或 redux-saga。此外,在第二个代码块中,变量 data 包含一个 Promise。
-
@atiqorin 我收到错误,但可能是因为找不到“数据”。
标签: javascript json react-native redux react-redux