简体   繁体   English

页面加载后反应添加路由

[英]React add a Route after page has loaded

I have an API with a list of names (which could change) I then want to create routes from that list but I keep getting route not found error.我有一个带有名称列表(可能会更改)的 API 然后我想从该列表中创建路由,但我不断收到找不到路由的错误。 However when manually adding the route for a name it works.但是,当手动添加名称的路由时,它可以工作。 How do I add a route after the page has loaded to make it work This is my code below如何在页面加载后添加路由以使其工作这是我的代码

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>
    );
}

Issue问题

The React render function is a synchronous, pure function, it can't wait for asynchronous logic to complete. React 渲染 function 是同步的,纯 function,它不能等待异步逻辑完成。 The json value is reset to an empty array each render cycle. json值在每个渲染周期重置为空数组。

The route mapping only needs to return the Route components that need to be rendered, using ReactDOM here isn't very valid.路由映射只需要返回需要渲染的Route组件,这里使用ReactDOM不是很有效。

Solution解决方案

Use component state to store the fetched data and a mounting useEffect hook to make the fetch request.使用组件 state 来存储获取的数据并使用挂载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>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM