最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I access a local JSON file with Redux to use throughout my React app? - Stack Overflow

programmeradmin3浏览0评论

I have a react app using Redux, and for testing purposes I created a local JSON file that sits inside a folder called data from within my app.

I'm trying to pass that JSON data to Redux so that I can access it and then use it to map out and display items in a separate ponent, but I have no idea how to do this. Can anyone provide examples or resources on how to acplish this?

I have a react app using Redux, and for testing purposes I created a local JSON file that sits inside a folder called data from within my app.

I'm trying to pass that JSON data to Redux so that I can access it and then use it to map out and display items in a separate ponent, but I have no idea how to do this. Can anyone provide examples or resources on how to acplish this?

Share Improve this question asked Jun 28, 2019 at 16:23 JoshJosh 1,2355 gold badges27 silver badges52 bronze badges 1
  • require('./data/thejson.json'); – Siri Commented Jun 28, 2019 at 16:25
Add a ment  | 

3 Answers 3

Reset to default 5

Like the user Sreeram said in the ments, you can directly require or import the json file, after which you will have access to it like any other object.

This means you can use it to initialize your state in your reducer.

const testData = require('./data/thejson.json');

// use testData as the default argument, which will be used if state is undefined (as it will be when the app starts 
function someReducer(state = testData , action) {
  switch (action.type) {
    // some code here.. 
  }
}

Add that json to the initial state of the store. So whenever your app starts it sets the initial state from the json and then use can use it anywhere in your app.

createStore(reducer,  require('your file path')

Is your data for dev purposes? or is it going to be included in production?
Keep in mind the size of the json

If you are using Typescript at least to 2.9 you can set: "resolveJsonModule": true, flag. and then import it:

import data from 'path/to/data.json';

If you are using webpack, since version 2, webpack includes json-loader

import data from 'path/to/data.json';

You could also serve it, I can't remember well but there's a way to serve static content with webpack dev server, which uses an express app under the hood that can be configured and then you can fetch it. I hope that helps.

发布评论

评论列表(0)

  1. 暂无评论