简体   繁体   English

如何使用带有 react-router-dom 的全局 state 显示模式?

[英]How to show modals using global state with react-router-dom?

My React app uses react-router-dom for navigation.我的 React 应用程序使用 react-router-dom 进行导航。 Within each of the different components for these routes there is the potential need to show some form of Error Modal component when something goes wrong.在这些路由的每个不同组件中,当出现问题时,可能需要显示某种形式的错误模态组件。 Instead of needing to import the same Error Modal into every component that needs it, manage state within the parent and declare toggle functions, I would like to do this once outside of all other components and just show the generic Error Modal when needed.无需将相同的错误模式导入每个需要它的组件,在父级中管理 state 并声明切换函数,我想在所有其他组件之外执行一次,并在需要时显示通用错误模式。

I suspect I may need to use Context API but I haven't used it before.我怀疑我可能需要使用 Context API 但我之前没有使用过它。

I found this article but I'm not sure how to implement this with my application that has multiple routes.我找到了这篇文章,但我不确定如何使用具有多条路由的应用程序来实现它。

Ideally I would like to trigger the modal from my axios interceptor in my index.js and have the modal show on top of whatever page the user is on.理想情况下,我想从 index.js 中的 axios 拦截器触发模式,并在用户所在的任何页面顶部显示模式。

index.js:索引.js:

    //imports...
    axios.interceptors.response.use(undefined, err => {
      if (err.response.status === 500) {
        // Set show state for error modal here
      }
    
      return Promise.reject(err); 
    });

    ReactDOM.render(<App />, document.getElementById('root'));

App.js:应用程序.js:

  import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
  // other imports...

  const App = () => {
    return (    
        <Router>
              <Routes>
                <Route path='/page1' element={<Page1 />}></Route>
                <Route path='/page2' element={<Page2 />}></Route>
              </Routes>
          </Router>     
      );
  };

I was actually able to solve a similar problem to this using the context API. See below for a brief explanation:我实际上能够使用上下文 API 解决与此类似的问题。请参阅下面的简要说明:

Create your ModalProvider创建你的 ModalProvider

export const ModalProvider = (props) => {
    const createModal = () => { // ...some modal init code here }
    return (
        <ModalContext.Provider value={{ createModal }}>
            <Modal/>
            {props.children}
        </ModalContext.Provider>
    )
}

You can then wrap your App in this provider and you should have access to the createModal function when accessing context.然后,您可以将您的应用程序包装在该提供程序中,并且在访问上下文时您应该有权访问 createModal function。 Hope this helps!希望这可以帮助!

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

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