gpt4 book ai didi

javascript - ReactJs中通过循环路由路径和组件名

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:08 25 4
gpt4 key购买 nike

这是我的路由文件编码。我必须通过在 asp.net 中从后端获取详细信息来创建所有路由。在这里,我从后端正确获取详细信息。这是我的菜单列表 [Contacts, Pipelines, Stages ]

import * as React from 'react';
import { BrowserRouter, Redirect, Route } from 'react-router-dom';
import { Layout,LayoutLogin } from './components/Layout';
import { Contacts } from './components/Contact';
import { Stages } from './components/Stage';
import { Pipelines } from './components/Pipeline';
import { Workspace } from './components/workspace';
import { NoMatch } from "./components/NoMatch"
import { Switch } from 'react-router';



var renderArea;

renderArea = <Layout>
<Switch>
<Route exact path='/' component={Workspace} />
<Route exact path='/Contacts' component={Contacts} />
<Route path='/Stages' component={Stages} />
<Route exact path='/Pipelines' component={Pipelines} />
<Route component={NoMatch} />

</Switch>
</Layout>;

export const routes = renderArea

这是我尝试路由路径和组件的代码。

import * as React from 'react';
import { BrowserRouter, Redirect, Route } from 'react-router-dom';
import { Layout,LayoutLogin } from './components/Layout';
import { Contacts } from './components/Contact';
import { Stages } from './components/Stage';
import { Pipelines } from './components/Pipeline';
import { NoMatch } from "./components/NoMatch"
import { Switch } from 'react-router';

import * as axios from 'axios';

var renderArea;
let renderMenuArea;
function listOfMenus() {
axios.default({
method: 'post',
url: '/Access/GetAllMenusForRoutes',
}).then(data => {
debugger
if (data.data.status == 'success') {
var listOfallMenus = data.data.listOfallMenus;
renderMenuArea = listOfallMenus.map((menu: any) => {
return (<Route key={menu.name} exact path={'/' + menu.name + ''} component={menu.name} />)
})
}
});
return renderMenuArea;
}



renderArea = <Layout>
<Switch>
<Route exact path='/' component={Workspace} />

{this.listOfMenus()}


<Route component={NoMatch} />

</Switch>
</Layout>;

export const routes = renderArea

此代码无效。返回函数数据总是未定义请建议我通过修改我的代码来获取返回数据,或者有什么方法可以实现我的代码目的?

最佳答案

listOfMenus 函数使用 axios 进行异步调用。所以renderMenuArea赋值的代码片段就是axios调用成功。由于调用是异步的,因此 renderMenuArea 在 axios 中的 promise 被 resolved 之前被返回。

解决此问题的最佳方法是使用适当的状态管理框架,例如 Redux存储数据并有效地管理您的 View 。

解决方法是按以下方式使用 async/await:

async function listOfMenus() {
await axios.default({
method: 'post',
url: '/Access/GetAllMenusForRoutes',
}).then(data => {
debugger
if (data.data.status == 'success') {
var listOfallMenus = data.data.listOfallMenus;
renderMenuArea = listOfallMenus.map((menu: any) => {
return (<Route key={menu.name} exact path={'/' + menu.name + ''} component={menu.name} />)
})
}
});
return renderMenuArea;
}

我强烈建议使用任何状态管理框架。

关于javascript - ReactJs中通过循环路由路径和组件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53154191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com