如何从URL获取.json数据?

时间:2019-02-12 17:20:46

标签: javascript json react-native redux react-redux

我在从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文件应该不错,因为它可以在小型应用程序中工作。

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试使用从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实现了一个reducer后,您可以调用fetchFavorites函数:它将发送请求并填充状态,但是您可以在reducer中进行此操作。