reactjs - React 将所有属性收集为一个 props 并将其放入组件中还是不?

标签 reactjs react-router-v4

我正在阅读 https://reacttraining.com/react-router/web/example/route-config 中的以下代码

const RouteWithSubRoutes = route => (
  <Route
    path={route.path}
    render={props => (
      // pass the sub-routes down to keep nesting
      <route.component {...props} routes={route.routes} />
    )}
  />
);

const RouteConfigExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/tacos">Tacos</Link>
        </li>
        <li>
          <Link to="/sandwiches">Sandwiches</Link>
        </li>
      </ul>

      {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)}
    </div>
  </Router>
);

请看第一行,为什么不是这样:

const RouteWithSubRoutes = ({route}) => (

据我所知,这个箭头函数应该获取一个参数,我们通常将其称为 props,它应该是一个包含所有放入的属性的集合。在这种情况下,props 应该包括“key”和所有属性“路线”。

在箭头函数的组件RouteWithSubRouters中,我们应该从集合props中过滤出有用的属性,比如route,所以我们将参数写成({route})。

我理解错了吗?为什么我改成({route})就显示错误?

================================================== ===================

谢谢大家!现在我知道了参数的魔力。我将代码更改如下:

const RouteWithSubRoutes = (routeProps) => {
    console.log(routeProps.aaa)
    return (
  <Route
    path={routeProps.path}
    render={props => (
      // pass the sub-routes down to keep nesting
      <routeProps.component {...props} routes={routeProps.routes} />
    )}
  />
);

const RouteConfigExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/tacos">Tacos</Link>
        </li>
        <li>
          <Link to="/sandwiches">Sandwiches</Link>
        </li>
      </ul>

      {routes.map((route, i) => <RouteWithSubRoutes key={i} aaa="bbb" {...route} />)}
    </div>
  </Router>
);

我得到打印‘bbb’~。 如果将参数命名为“props”,会更容易理解。

最佳答案

在此代码中route是一个对象,其中包含必须用于创建 <Route> 的值。自 props名称不明确并且在同一组件中使用,为了明确起见,可以将其定义为:

const RouteWithSubRoutes = routeProps => (
  <Route
    path={routeProps.path}
    render={props => (
      // pass the sub-routes down to keep nesting
      <routeProps.component {...props} routes={routeProps.routes} />
    )}
  />
);

或者使用解构( component 需要重命名为大写):

const RouteWithSubRoutes = ({ path, routes, component: Component }) => (
  <Route
    path={path}
    render={props => (
      <Component {...props} routes={routes} />
    )}
  />
);

const RouteWithSubRoutes = ({route}) => (...)将是一个错误,因为 routeProps反对RouteWithSubRoutes收到没有route属性。

关于reactjs - React 将所有属性收集为一个 props 并将其放入组件中还是不?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52954537/

相关文章:

javascript - React - 调用 history.push 后组件呈现错误

javascript - OpenAI ChatGPT (GPT-3.5) API 错误 404 : "Request failed with status code 404"

javascript - 避免 useEffect 在第一次加载时渲染?

javascript - 类型错误 : Cannot read property 'offsetParent' of null when navigatin to another page

javascript - React - 如何返回到上一个分页页面?

javascript - 使用 "push",网址发生变化,但我的整个页面变成空白

reactjs - react 路由器|私有(private)路由器上的调用功能

javascript - fetch 向后端发送错误的数据格式

javascript - Gatsby i18next 插件 无法生成 codeFrame

javascript - 具有动态路由的 react 路由器在浏览器直接链接上给出 404