reactjs - 反应路由器循环并返回
问题描述
我正在尝试使用循环从数组中返回我的路线。我有一个 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"}
]
}
解决方案
该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
.
推荐阅读
- javascript - React 不会从数组中删除项目
- c++ - 消息“错误:使用未声明的标识符 'assert'”
- c# - 为什么使用 TcpClient 发出 HTTP 请求会收到“301 Moved Permanently”错误?
- matplotlib - 如何使用 matplotlib 和 gridspec 仅将一个轴与其他轴隔开?
- java - 如何将输入数据传递给 Java 中现有的 tensorflow 2.x 模型?
- ios - 如何快速将参数传递给这种函数?
- html - 如何使用一个元素的孙子元素来切换前一个元素的孙子元素的类?
- python - 从 Excel 文件中绘制数据
- node.js - Mongoose 填充未提供连接结果
- c++ - g++:致命错误:无法执行'as':CreateProcess:没有这样的文件或目录编译终止