我有一个带有名称列表(可以更改)的API,然后我想从该列表创建路由,但我一直收到路由未找到错误。但是,当手动添加名称的路由时,它可以工作。如何在页面加载后添加路由以使其正常工作以下是我的代码
function App() {
let json =[]
fetch(`${baseURL}/applications/`).then(response =>{return response.json();}).then(data =>{json=data})
console.log("json =", json)
return (
<Router>
<div className="App">
<header className="App-header">
<Routes>
<Route path="/" exact element={<ApplicationsList/>}/>
<Route path={"/1080p-Lock"} exact element={<ApplicationPage name={"1080p-Lock"}/>}/>
{json.map(item => {ReactDOM.render(<Route path={"/" + item} exact element={<ApplicationPage name={item}/>}/>)})}
</Routes>
</header>
</div>
</Router>
);
}发布于 2021-11-22 18:21:01
问题
React呈现函数是一个同步的纯函数,它不能等待异步逻辑完成。在每个渲染周期中,json值将重置为空数组。
路由映射只需要返回需要呈现的Route组件,这里使用ReactDOM并不是很有效。
解决方案
使用组件状态存储获取的数据,并使用挂载useEffect挂钩发出获取请求。
function App() {
const [routes, setRoutes] = useState([]);
useEffect(() => {
fetch(`${baseURL}/applications/`)
.then(response => {
return response.json();
})
.then(data => {
setRoutes(data);
})
.catch(error => {
// handle any rejected Promises, etc...
});
}, []);
return (
<Router>
<div className="App">
<header className="App-header">
<Routes>
<Route path="/" element={<ApplicationsList/>}/>
<Route path={"/1080p-Lock"} element={<ApplicationPage name={"1080p-Lock"}/>}/>
{routes.map(item => (
<Route path={"/" + item} element={<ApplicationPage name={item}/>}/>
))}
</Routes>
</header>
</div>
</Router>
);
}https://stackoverflow.com/questions/70069921
复制相似问题