React can't deconstruct restProps in Edge

好久不见. 提交于 2020-06-23 04:38:22

问题


I've a problem and somehow I just can't solve it. I tried everything for hours but I just don't find a solution. It worked in older projects, but doesn't work with a brand new react project created with create-react-app.

Consider the following code:

App.js:

function App() {
  const test = {
    test1: {},
    test2: {}
  };
    return (
        <div className="App">
            Cool!
          <Test
            name1="cool1"
            {...test}
          />
        </div>
    );
}

export default App;

Nothing big here. If I start the project with npm start, everything works as expected and I see the "Cool!" in the Browser. (Test is defined below, its a simple component that returns a div.)

Now, if I try to use ...props in my function parameters for Test, like this:

export const Test = ({name1, ...props}) => {
    return (
        <div>yay! {props.name1}</div>
    )
};

It works fine in chrome, but Microsoft edge says:

SCRIPT1028: SCRIPT1028: Expected identifier, string or number

I use this syntax in older projects, created with older version of create-react-app without any problem, so I'm not too sure where the problem is. Could this even be a general bug in the create-react-app, since the project is literally created with it and has no libraries added to it.

Best Regards and thanks for any help!


回答1:


After searching for a while, I found a solution for the problem. It works without ejecting.

The Problem & the way I found a solution:

At some point in the past, react decided to remove some babel presets from their react-app presets. I compared the "babel-preset-react-app" (folder inside node_modules) from an older project, with the babel-presets from a newly created react app (created with create-react-app v3.4). By comparing the package.json from the babel-preset-react-app from both applications, I found out that in the newer version, there are much less babel plugins installed.

The solution: Install the @babel/plugin-proposal-object-rest-spread (and maybe also the @babel/plugin-transform-spread just to be sure) by running:

npm install @babel/plugin-proposal-object-rest-spread @babel/plugin-transform-spread

Once done, simply add them as plugins inside the package.json of your react app, below the imported presets from react:

"babel": {
    "presets": [ // This line should already be there if you created your project with CRA
      "react-app"
    ],
    "plugins": [
      "@babel/plugin-transform-spread",
      "@babel/plugin-proposal-object-rest-spread"
    ]
  }

I hope this helped!



来源:https://stackoverflow.com/questions/60417760/react-cant-deconstruct-restprops-in-edge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!