我在从URL获取数据时遇到问题。当我将数据写入文件时,应用程序运行良好,但是当我尝试从 URL 调用相同的数据时,我收到错误。
我用小应用程序做了一个测试,其中所有内容都在 App.js 文件中,它有效。但是新应用程序有点分为多个文件,这就是问题开始的地方。
以下是事件.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文件应该没问题,因为它适用于小应用程序。
我认为您正在尝试使用从 URL 加载的 json 文件的内容初始化状态:如果我是你,我会创建一个专门用于执行此操作的操作。你需要一个库来处理异步进程,比如redux-thunk或redux-saga。
下面是一个使用 redux-thunk 的快速示例:
// store
import thunk from 'redux-thunk'
import { createStore, applyMiddleware } from 'redux'
import reducer from 'state/reducers'
export const configureStore = () => {
/* thunk is a redux middleware: it lets you call action creators that return a function instead of
an object. These functions can call dispatch several times (see fetchFavorites) */
const middlewares = [thunk]
let store = createStore(reducer, applyMiddleware(...middlewares))
return store
}
// actions
// standard action returning an object
export const receiveFavorites = function(response){
return {
type: "RECEIVE_FAVORITES",
response
}
}
// this action returns a function which receives dispatch in parameter
export const fetchFavorites = function(){
return function(dispatch){
console.log('send request')
return fetch('http://some-url.com/test.json')
.then(response => response.json())
.then(response => {
dispatch(receiveFavorites(response))
})
.catch(error => {
console.log(error)
})
}
}
现在,通过为操作RECEIVE_FAVORITES实现的化简器,您可以调用函数 fetchFavorites:它将发送请求并填充状态,无论您在化简器中执行什么。