【问题标题】:How to fetch .json data from URL?如何从 URL 获取 .json 数据?
【发布时间】: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


【解决方案1】:

我认为您正在尝试使用从 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 中执行此操作。

【讨论】:

    猜你喜欢
    • 2014-03-13
    • 2022-12-22
    • 1970-01-01
    • 2019-01-19
    • 2018-09-22
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多