0

我在我的应用程序中使用 React 16、React-router-dom 4 和 Mobx。

我有这个私人路线的代码:

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" />
    }

};

这是路由设置:

export const history = createHistory();

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

由于某种原因,私有路由中不存在历史记录道具,因此我无法使用 this.props.history.push 函数以编程方式重定向。不过,道具确实会传递到“正常”路线。

我的代码有什么问题?

4

1 回答 1

2

下面使用:

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

用 withRouter 包裹组件。

withRouter(component_name)
于 2018-12-04T00:21:20.537 回答