我有很多这样的路线
babel --watch src/file_will_be_compiled.js --out-dir src --plugins @babel/plugin-transform-react-jsx
它们工作正常,但是如果没有设置属性,我希望将它们全部重定向到“ / dashboard”
我尝试过这个:
function sort(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].title !== 'Test') {
arr[i] = {
...arr[i],
data: sortByType(arr[i].data),
full: sortByType(arr[i].full)
};
}
}
return arr;
}
失败并失败
我正在使用 “ react-router-dom”:“ ^ 4.3.1”, “ react-router-redux”:“ ^ 5.0.0-alpha.9”, “ react”:“ ^ 16.13.1”,
答案 0 :(得分:1)
创建一个组件,如果该属性不存在,它将重定向到仪表板(或指定的任何路径),否则它将呈现路线本身。
export const ProtectedRoute = ({comp: Component, redirectTo, path, key}) => {
const propertyExists = "...";
if (propertyExists) return <Route path={path} component={Component} key={key}></Route>;
else return <Redirect to={redirectTo || "/dashboard"}/>
};
现在在路线内
<Switch>
<Route path="/dashboard" component={Dashboard} key="dashboard" />
<ProtectedRoute path="/projects" component={UserProjects} key="userprojects" />
<ProtectedRoute path="/compute/servers" component={ProjectServerList} key="projectserverlist" />
<ProtectedRoute path="/compute/snapshots" component={ServerSnapshotList} key="ServerSnapshotList" />
<ProtectedRoute path="/compute/keypairs" component={KeypairList} key="KeypairList" />
答案 1 :(得分:0)
我做了一些修改,希望它是您想要的
{myproperty ? (
<Switch>
<Route path="/dashboard" component={Dashboard} key="dashboard" />
<Route path="/projects" component={UserProjects} key="userprojects" />
<Route path="/compute/servers" component={ProjectServerList} key="projectserverlist" />
<Route path="/compute/snapshots" component={ServerSnapshotList} key="ServerSnapshotList" />
<Route path="/compute/keypairs" component={KeypairList} key="KeypairList" />
</Switch>
) : (
<Route component={Dashboard} key="dashboard" />
)}
如果“ myproperty”具有值,则一切将正常进行,否则将呈现component = {Dashboard}