无法在React中获取数组状态值

时间:2019-02-27 00:06:18

标签: javascript arrays reactjs webpack

当我尝试获取值...this.state.users时,在react中显示错误

反应码

handleChange(i, e) {
        const { name, value } = e.target;
        let users = [...this.state.users];
        users[i] = { ...users[i], [name]: value };
        this.setState({ users });
    }

我的webpack文件

const path = require('path');
module.exports = (env) => {
    const isProduction = env === 'production';
    return {
        entry: './src/index.js',
        output: {
            path: path.join(__dirname, 'public'),
            filename: 'bundle.js',
        },
        module: {
            rules: [
                {
                    loader: 'babel-loader',
                    test: /\.js$/,
                    exclude: /node_modules/,
                },
                {
                    test: /\.css$/,
                    use: ['style-loader', 'css-loader'],
                },
            ],
        },
    };
}

错误是

 ERROR in ./src/components/Index.js
[1] Module build failed: SyntaxError: E:/Program/reactjs/check/client/src/components/Index.js: Unexpected token (47:15)

请帮助我解决此错误

1 个答案:

答案 0 :(得分:0)

您似乎需要正确配置babel。 根据{{​​3}},您需要确保已安装Stage-0预设:

npm install --save-dev babel-preset-stage-0

并配置:

{
  "presets":[
    "es2015", "react", "stage-0"
  ]
}

但是,如果您使用的是Babel v7或更高版本,则必须使用this post

npm install --save-dev @babel/plugin-proposal-object-rest-spread

并将其放入您的.babelrc文件:

{
  "plugins": ["@babel/plugin-proposal-object-rest-spread"]
}