首页 > 解决方案 > 反应路由器循环并返回

问题描述

我正在尝试使用循环从数组中返回我的路线。我有一个 app.js 文件,其中我的代码是这样的:

  return (          
      <Switch>
        <Route path="/" component={() => <HomePage />} exact />
        <Route path="/chooseStyles" component={FormContainer} />
        <Route path="/heightAndWeight" component={FormContainer} />
        <Route path="/bodyShape" component={FormContainer} />
        </Switch>
);

我正在尝试使我的路线动态并通过数组循环。但我无法让它发挥作用。为此,我正在尝试以下代码:

return (          
      <Switch>
         {a.map((b,i) => <Route path={b[i].url} component={() => <Global_Container name={a[0].path} />}  />)}
        <Route path="/" component={() => <HomePage />} exact />
        <Route path="/chooseStyles" component={FormContainer} />
        <Route path="/heightAndWeight" component={FormContainer} />
        <Route path="/bodyShape" component={FormContainer} />
        </Switch>
);

使用上面的代码我得到了错误。我创建了一个像这样的变量:

var a = [{"url":"/global","path":"maternityFit"},
            {"url":"/global1","path":"clothFit"}
        ]

当我使用这样的代码时,我的代码工作正常:

  {a.map((b,i) => <Route path={a[0].url} component={() => <Global_Container name={a[0].path} />}  />)}

我不知道如何使它适用于我的情况。我在代码块中声明我的 var a:

export default function App() {
  var a = [{"url":"/global","path":"maternityFit"},
            {"url":"/global1","path":"clothFit"}
        ]
}

标签: reactjsloopsroutes

解决方案


map功能未正确使用。b具有数组的当前值,您不应该这样做b.[index]b已经是做的结果a[index];只是使用它。上的文档map

相反,您应该这样做:

{a.map((b) => (
  <Route path={b.url} component={() => <Global_Container name={b.path} />}  />
  //           ^ b is the object not array                     ^ Use b here instead of a
))}

为了进一步可视化正在发生的事情,请考虑以下内容:

var myArray = [{ val1: 'foo' }, { val1: 'bar' }]

myArray.map((obj, index) => {
  console.log('myArray: ', myArray); // Still the full array
  console.log('obj: ', obj); // The current value in the loop
  console.log('index: ', index); // The current index in the loop
});

所以问题是你想像使用obj它一样使用myArray. 但相反,您可以跳过输入的额外字符,myArray[index]只需使用obj.


推荐阅读