反应路由器循环并返回

时间:2020-03-17 18:04:24

标签: reactjs loops routes

我正在尝试使用循环从数组返回路由。我有一个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"}
        ]
}

1 个答案:

答案 0 :(得分:1)

map函数使用不正确。 b具有数组的当前值,您不应该这样做b.[index]b已经是执行a[index]的结果;只需使用它即可。 Documentation on 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