简体   繁体   English

在React.js中更新状态时出现语法错误

[英]Syntax error while updating state in React.js

the following code show me an syntax error while updating the state in React.js. 以下代码向我展示了在React.js中更新状态时的语法错误。

import { FETCH_POSTS } from '../actions/index';
const INITIAL_STATE = { all:[], post: null};

export default (state=INITIAL_STATE,action) => {
  switch(action.type){
    case FETCH_POSTS:
    return { ...state, all: action.payload.data };
    default:
    return state;
  }
}

it show me an error on return { ...state,all:action.payload.data }; 它向我显示return { ...state,all:action.payload.data };错误return { ...state,all:action.payload.data };

According to the ES6 specification, the spread operator can be applied only to iterable objects ( https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator ). 根据ES6规范, the spread operator can be applied only to iterable objectshttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator )。 You can use Object.assign or consider something like https://github.com/sebmarkbage/ecmascript-rest-spread with your transpiler. 您可以使用Object.assign或将Transpiler考虑为https://github.com/sebmarkbage/ecmascript-rest-spread之类的东西。

Make use of Object.assign() to update and return the state 利用Object.assign()更新并返回状态

export default (state=INITIAL_STATE,action) => {
  switch(action.type){
    case FETCH_POSTS:
    return Object.assign({}, state, {all: action.payload.data});
    default:
    return state;
  }
}

I had the same issue with the same code as yours when I started my own project after finishing this course https://www.udemy.com/react-redux 完成本课程后,当我启动自己的项目时,我遇到了与您相同的代码问题, https://www.udemy.com/react-redux

I figured out that I forgot to install preset-1 https://www.npmjs.com/package/webpack-preset-babel-stage-1 and include it in webpack.config.js 我发现我忘记安装预置1 https://www.npmjs.com/package/webpack-preset-babel-stage-1并将其包含在webpack.config.js中

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

Well, I came across the same problem. 好吧,我遇到了同样的问题。 Do remember to install "babel-preset-stage-1" in your npm packages and use it as "stage-1" while setting presets for babel. 切记在npm软件包中安装“ babel-preset-stage-1”,并在设置babel预设时将其用作“ stage-1”。 It will work. 它会工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM