React 无法在 Edge 中解构 restProps

React can't deconstruct restProps in Edge

我有一个问题,但我无法解决它。我尝试了几个小时,但就是找不到解决方案。它适用于较旧的项目,但不适用于使用 create-react-app 创建的全新 React 项目。

考虑以下代码:

App.js:

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

export default App;

没什么大不了的。如果我使用 npm start 启动项目,一切都会按预期进行,并且我会在浏览器中看到 "Cool!"。 (测试定义如下,它是一个returns一个div的简单组件。)

现在,如果我尝试在测试函数参数中使用 ...props,如下所示:

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

它在 chrome 中运行良好,但 Microsoft edge 显示:

SCRIPT1028: SCRIPT1028: Expected identifier, string or number

我在旧项目中使用这种语法,使用旧版本的 create-react-app 创建没有任何问题,所以我不太确定问题出在哪里。这甚至可能是 create-react-app 中的一般错误,因为项目实际上是用它创建的,没有添加任何库。

此致,感谢您的帮助!

经过一段时间的搜索,我找到了解决问题的方法。 不用弹出也能用

问题和我找到解决方案的方式:

在过去的某个时候,react 决定从他们的 react-app 预设中删除一些 babel 预设。我将旧项目中的 "babel-preset-react-app"(node_modules 内的文件夹)与新创建的 React 应用程序(使用 create-react-app v3.4 创建)中的 babel-presets 进行了比较。通过比较两个应用程序的 babel-preset-react-app 中的 package.json,我发现在较新的版本中,安装的 babel 插件要少得多。

解决方法: 通过 运行:

安装@babel/plugin-proposal-object-rest-spread(也可能是@babel/plugin-transform-spread)
npm install @babel/plugin-proposal-object-rest-spread @babel/plugin-transform-spread

完成后,只需将它们作为插件添加到您的 React 应用程序的 package.json 中,在从 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"
    ]
  }

希望对您有所帮助!