【问题标题】:React spread operator (...rest) alternatives?反应传播运算符(...休息)的替代品?
【发布时间】:2018-07-31 07:19:03
【问题描述】:

我无法在我的管道中包含 babel-preset-stage-3。传播运算符有什么替代方案吗?

我正在尝试编译以下代码,但出现语法错误:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

【问题讨论】:

  • 简单地使用两个参数怎么样?
  • @Bergi 可以传入任意数量的参数,由函数的用户指定。
  • 我的意思是const privateRoute = (component, rest) =&gt; …

标签: javascript reactjs ecmascript-6 react-router


【解决方案1】:

使用lodash.omit

const PrivateRoute = (props) => {
  const Component = props.component;
  const rest = omit(props, ['component'])
  return (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);
}

【讨论】:

  • 这是有效的 jsx 语法,不依赖 babel-preset-stage-3。
  • babel-repl: goo.gl/VNCnvW
  • @BryanChen 这就是 JSX 属性传播,和 ES 对象传播的思路一样,但由 react-preset-react 处理。
【解决方案2】:

安装babel-plugin-transform-object-rest-spread

npm install --save-dev babel-plugin-transform-object-rest-spread

在您的 .babelrc 文件中,添加以下行

{
  "plugins": ["transform-object-rest-spread"]
}

【讨论】:

    【解决方案3】:

    为简单起见尝试使用此功能:

                        var vals;
            console.log(typeof out)
            isobj = typeof(out) === 'object'?true:false
    
    
                    if (Object.values) {
                        vals = Object.keys(obj).map(function(i) { 
               if(isobj)
                 out[i] = obj[i]; 
    
                        })
                    }else
                        vals= Object.values(obj) 
                    return vals;
    ````}
    

    【讨论】:

    • 这样简单吗?
    • 尝试使用更好的格式并解决代码中的错误。
    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 2022-07-28
    • 2023-04-04
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多