将 JSON 文件加载到 React 组件状态 | Wepback2

Posted

技术标签:

【中文标题】将 JSON 文件加载到 React 组件状态 | Wepback2【英文标题】:Loading JSON file into React Component state | Wepback2 【发布时间】:2017-11-21 16:25:34 【问题描述】:

一段时间以来,我一直在尝试将本地 JSON 文件导入我的 react 组件状态,无论我用多少谷歌搜索和尝试 - 我似乎都无法让它工作。这是我的 json 文件:


  "products": [
    "id": 1, "category": "paint", "name": "clowd", "type": "matt emulsion", "stocked": true, "size": "100x130", "thumbnail": "23-sm.png", "previewImg": "23.png",
    "id": 2, "category": "paint", "name": "dålig sikt", "type": "matt emulsion/olja/akryl", "stocked": true, "size": "100x130", "thumbnail": "24-sm.png", "previewImg": "24.png",

    "id": 25, "category": "print", "name": "MIMI | 2nd edition", "type": "akvarellppr, 70x100", "limited": "30", "available": "28",  "price": "3,000", "stocked": true,  "thumbnail": "mimisecond-sm.jpg", "previewImg": "mimisecond.jpg",
    "id": 26, "category": "print", "name": "max", "type": "uppspänd canvas, 95x120", "limited": "30", "available": "28",  "price": "7,000", "stocked": true,  "thumbnail": "max-sm.jpg", "previewImg": "max.jpg",

    "id": 38, "category": "places", "stocked": true, "desc": "Vernisage Strössel @ Linnégatan, sthlm 2015", "thumbnail": "17.png", "previewImg": "17.png",
    "id": 39, "category": "places", "stocked": true, "desc": "Max @ Nybergsgatan, sthlm 2016", "thumbnail": "26.png", "previewImg": "26.png"
  ]

这是我的反应组件:

import React,  Component  from 'react';

import data from 'data.json';
console.log(data);

// Component import
import Menu from './components/menu';
import Footer from './components/footer';
import ProductContainer from './components/productContainer';
import CategoryContainer from './components/categoryContainer';

class Archive extends React.Component 
  constructor(props)
    super(props);
    this.state = 
      products: data,
      category: ""
    ;
    this.filterHandler = this.filterHandler.bind(this);
  

  // Set component state to the currently clicked "cat" (CategoryItem)
  filterHandler(tag)
    this.setState(
      category: tag
    )
  

  render() 
    // 1. Render CategoryContainer with props products and filterHandler function to show all uniqe CategoryItems and filter products based on category
    // 2. Render ProductContainer based on category. If this.state.category.length is true - filter "prod" & where prod.categories is same type and name as this.state.category : else render all this.state.categories that matches "paint".
    return (
      <div>
        <Menu />
        <div className="archive-container">
          <div className="archive-wrapper">
            <CategoryContainer
              filterHandler=this.filterHandler
              products=this.state.products
            />
            <br/><br/>
            <ProductContainer
              products=this.state.category.length
                ? this.state.products.filter((prod) => prod.category === this.state.category)
                : this.state.products.filter((prod) => prod.category === 'paint')
              
            />
          </div>
        </div>
        <Footer />
      </div>
    );
  ;
;

export default Archive;

这是我的 webpack2 文件:

// DEVELOPMENT

const webpack = require('webpack');
const path = require('path');

const entry = [
    'webpack-dev-server/client?http://localhost:8080', // bundle the client for webpack-dev-server and connect to the provided endpoint
    'webpack/hot/only-dev-server', // bundle the client for hot reloading only- means to only hot reload for successful updates
    './app.js'
]

const output = 
    path: path.join(__dirname, 'dist'),
    publicPath: '/dist',
  filename: 'bundle.min.js'


const plugins = [
    new webpack.HotModuleReplacementPlugin(), // enable HMR globally
    new webpack.NamedModulesPlugin() // prints more readable module names in the browser console on HMR updates
]

const config = 
  context: path.join(__dirname, 'src'),
  entry: entry,
    output: output,
    devtool: "inline-source-map",
  module: 
    rules: [
            
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                include: path.join(__dirname, 'src'),
                use: 
                    loader: "babel-loader"
                
            ,
            
              test: /\.(png|jpg|gif)$/,
              use: [
                loader: 'url-loader',
          options:  limit: 10000, name: './images/[name].[ext]' 
              ]
            ,
            
                test: /\.(sass|scss)$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader'
                ]
            
        ]
  ,
    plugins: plugins,
    externals: 
      jquery: 'jQuery'
    


module.exports = config

我得到错误:

如果我将 json 文件更改为 javascript 对象并直接将其输入到构造函数中:

constructor(props)
    super(props);
    this.state = 
      products: [
        id: 1, category: 'paint', name: 'clowd', type: 'matt emulsion', stocked: true, size: '100x130', thumbnail: '23-sm.png', previewImg: "23.png",
        id: 2, category: 'paint', name: 'dålig sikt', type: 'matt emulsion/olja/akryl', stocked: true, size: '100x130', thumbnail: '24-sm.png', previewImg: "24.png",
        id: 3, category: 'paint', name: 'dålig sikt', type: 'matt emulsion/olja/akryl', stocked: true, size: '100x130', thumbnail: '25-sm.png', previewImg: "25.png",
        id: 4, category: 'paint', name: 'pink', type: 'matt emulsion', stocked: true, size: '100x130', thumbnail: '1-sm.png', previewImg: "1.png",
        id: 5, category: 'paint', name: 'pink', type: 'matt emulsion', stocked: true, size: '100x130', thumbnail: '27-sm.png', previewImg: "27.png",
        id: 6, category: 'paint', name: 'pinks', type: 'matt emulsion', stocked: true, size: '100x130', thumbnail: '2-sm.png', previewImg: "2.png"
      ],
      category: ""
    
    this.filterHandler = this.filterHandler.bind(this);
  

然后它工作正常。但我希望它在一个单独的 json 文件中,这样它就不会被 捆绑 ,因此客户端将项目添加到列表中会更容易。

也许有一种更聪明的方法可以做到这一点,我是 react 和 webpack 的新手,并希望学习 .. 非常适合任何形式的输入。谢谢!

【问题讨论】:

由于您根据 json-loader 文档 (github.com/webpack-contrib/json-loader) 使用 webpack2,因此您应该能够直接在您的 react 组件中加载 json 文件,而无需任何额外的配置。您是否尝试过从 webpack 配置中删除 json-loader 并直接导入文件? 这个模块转译成js sn-p,以module.exports开头,请直接试试import data from 'data.json' @JiuJitsuCoder 谢谢!我从 webpack 文件中删除了 json-loader @DanielMizerski ..并将导入更改为“从'data.json'导入数据;”但出现错误:“无法解析 '/Applications/MAMP/htdocs/magdan/src' 中的 'data.json'”。我的 data.json 文件位于“'/Applications/MAMP/htdocs/magdan/src”中。 @DanielMizerski 对!解决了该错误,但出现了新错误(我的生活故事)..:“warning.js:36 警告:道具类型失败:object 类型的无效道具products 提供给CategoryContainer,预期array。”和“未捕获的 TypeError:this.state.products.filter 不是函数” 【参考方案1】:

(如果有人来解决这个问题......在问题的 cmets 中是对在 webpack 2 中导入 json 文件时常见错误的修复)

您的Archive.state 看起来像:


   products:  products: [ (your rest of array) ] ,
   category: ""

你的错误是

 this.state = 
   products: data,
   category: ""
 ;

应该是:

 this.state = 
   products: data.products,
   category: ""
 ;

【讨论】:

当您在互联网上随机帮助某人时的那种感觉... ;)

以上是关于将 JSON 文件加载到 React 组件状态 | Wepback2的主要内容,如果未能解决你的问题,请参考以下文章

当另一个组件的状态发生变化时如何重新加载组件 React

React 可加载 JSON 映射文件,其中包含从多个位置引用的组件

如何在将 json 发布到 React 组件状态之前对其进行处理?

将 JSON 文件中的项目数据动态加载到 React

在 React 中将组件状态转换为 JSON

Graphql,react-apollo如何在加载组件状态时将变量传递给查询