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

时间:2017-06-19 12:38:58

标签: json reactjs webpack webpack-2

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

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;

这是我的反应组件:

// 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

这是我的webpack2文件:

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);
  }

我收到错误: enter image description here

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

NumberFormatter

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

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

1 个答案:

答案 0 :(得分:2)

(如果有人来解决此问题...在问题评论中修复了在json中导入webpack 2文件时常见错误

您的Archive.state看起来像是:

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

您的错误是

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

应该是:

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