在页面加载后反应添加路由

React add a Route after page has loaded

我有一个 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>
    );
}

问题

React 渲染函数是一个同步的纯函数,它不能等待异步逻辑完成。 json 值在每个渲染周期重置为一个空数组。

路由映射只需要return需要渲染的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>
  );
}