【问题标题】:Redirect from React's Context API component从 React 的 Context API 组件重定向
【发布时间】:2020-08-22 16:03:36
【问题描述】:

在从 cookie 更新状态失败后,我正在尝试从我的上下文重定向。

import React, { createContext, Component } from 'react';
import { withRouter } from "react-router-dom";
import Cookies from 'universal-cookie';

export const MyContext = createContext();

const cookies = new Cookies();

class MyProvider extends Component {
  componentDidMount() {
    this.setStateFromCookie();
  }

  setStateFromCookie = () => {
    try {
      this.setState({ data: cookies.get('my-cookie')['data'] });
    } catch(error) {
      console.log(error);
      this.props.history.push('/');
    }
    return 
  };

  render() {
    return (
      <MyContext.Provider value={{...this.state}}>
        {this.props.children}
      </MyContext.Provider>
    );
  }
}

export default withRouter(MyProvider);

我在 this.props.history.push('/') 上使用 withRouter 挂钩,因为上下文正在包装路由器

class MyApp extends Component {
  render() {
    return (
      <BrowserRouter>
        <MyProvider>
          <div className="MyApp">
            <Router>
              <Route exact path='/' component={Index} />
              <Route exact path='/dashboard' component={Dashboard} />
            </Router>
          </div>
        </MyProvider>
      </BrowserRouter>
    );
  }
}
export default MyApp;

问题是在错误之后重定向到主页,但主页没有呈现。我仍然看到仪表板页面。

知道发生了什么以及如何解决这个问题

【问题讨论】:

    标签: reactjs react-native react-router react-context


    【解决方案1】:

    问题是你有一个嵌套的路由器包裹你的路由。你需要删除它,然后一切都会正常工作

      <BrowserRouter>
        <MyProvider>
          <div className="MyApp">
              <Route exact path='/' component={Index} />
              <Route exact path='/dashboard' component={Dashboard} />
          </div>
        </MyProvider>
      </BrowserRouter>
    

    当您使用嵌套路由器并尝试从 Provider 导航时,Provider 使用的历史记录由 BrowserRouter 提供,因此它无法与依赖于内部 &lt;Router&gt; 的路由通信历史组件。

    使用包装组件的单个路由器解决了这个问题

    【讨论】:

    • 你是什么意思?如果我删除 BrowserRouter this.props.history.push('/');在我的上下文中将不再起作用..
    • 你不要删除 BrowserRouter,删除路由器包装 &lt;Route&gt;。请检查帖子。我已经展示了它应该是什么样子
    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2020-07-17
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2021-04-25
    相关资源
    最近更新 更多