如何在同一文件中的组件外部使用 useState 变量?

问题描述 投票:0回答:1

我正在开发一个从 swiggy api 获取数据的项目,但现在我已经向该项目添加了路由,我不知道如何在组件之外添加 useState 变量,但在同一个文件中,我已经添加了代码帮帮我,我正在尝试访问 api 元素:,.

`const App = () => {
  const [api, setAPI_KEY] = useState(PUNE_API);

  const handleAPIKeyChange = (newAPIKey) => {
    console.log("API Key changed to:", newAPIKey);

    setAPI_KEY(newAPIKey);
  };

  return (
    <div className="app">
      <Header onAPIKeyChange={handleAPIKeyChange} />
      <Outlet/>
      
      <Footer />
    </div>
    
  );
  
};
const appRoute = createBrowserRouter([
  {
      path : "/",
      element : <App/>,
      errorElement : <RouterError/>,
      children:[
        {
          path : "/home",
          element : <BodyLayout api={api} />,
          
      },
        {
          path : "/",
           element : <BodyLayout api={api} />,
         
      },
        {
          path : "/about",
          element : <About/>,
      },
      {
        path : "/contact",
        element : <Contact/>,
       
      },
      {
        path : "/cart",
        element : <Cart/>,
       
      },
      {
        path : "/offers",
        element : <Offers/>,
       
      },
      ],
  },
  
 ])
const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(<RouterProvider router={appRoute}/>);

 `

我尝试了多种方法但没有成功。

javascript reactjs react-hooks react-router web-deployment-project
1个回答
0
投票

您可以创建自定义钩子来调用API并在任何React组件中使用返回的结果(API结果)。

© www.soinside.com 2019 - 2024. All rights reserved.