简体   繁体   English

反应:“历史”道具在私有路线中不可用

[英]React: “history” prop is not available in a private route

I'm using React 16, React-router-dom 4 and Mobx in my app. 我在我的应用程序中使用React 16,React-router-dom 4和Mobx。

I have this code for a private route: 我有用于私人路线的以下代码:

export default (props) => {

    console.log('props from private',props)//Here i can see that the component doesn't contain the "history" prop.

    const Component = props.component;  

    const match = props.computedMatch
    if (isValidated()) {
        return (
            <div>
                <div><Component  {...props} match={match} /></div>
            </div>
        )
    } else {
        return <Redirect to="/login" />
    }

};

This is the routing setup: 这是路由设置:

export const history = createHistory();

const AppRouter = () => (
  <Router history={history}>
    <Switch>
      <PrivateRoute  path="/" component={Chat} exact={true} />
      <Route path="/login" component={Login} />
    </Switch>
  </Router>
);

For some reason, the history prop just doesn't exist in the private route, therefore i'm unable to use the this.props.history.push function, to redirect programatically. 由于某种原因,历史记录道具在私有路由中根本不存在,因此我无法使用this.props.history.push函数以编程方式进行重定向。 The prop does get passed to a "normal" route though. 该道具确实传递到了“正常”路线。

What is wrong with my code? 我的代码有什么问题?

Use below: 在下面使用:

import {withRouter} from 'react-router-dom';

wrap component with withRouter. 用withRouter包装组件。

withRouter(component_name)

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

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