【问题标题】:React add a Route after page has loaded页面加载后反应添加路由
【发布时间】:2022-01-01 07:10:05
【问题描述】:

我有一个包含名称列表(可能会更改)的 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>
    );
}

【问题讨论】:

  • 你需要把你的 fetch 放在一个 useEffect 中,并存储在一个 useState 中。

标签: javascript reactjs web react-router react-router-dom


【解决方案1】:

问题

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 2017-12-08
    • 1970-01-01
    • 2020-11-06
    • 2020-07-11
    • 2023-02-13
    • 2021-09-25
    • 2020-02-14
    相关资源
    最近更新 更多