javascript - react : "history" prop is not available in a private route

标签 javascript reactjs react-router

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

我有一条私有(private)路线的代码:

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>
);

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

我的代码有什么问题吗?

最佳答案

使用如下:

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

用withRouter包裹组件。

withRouter(component_name)

关于javascript - react : "history" prop is not available in a private route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603767/

相关文章:

javascript - 如何使 React 组件更可重用?

javascript - 在多个组件中重复使用导航栏组件

javascript - document.querySelectorAll 仅在检查 DOM 后返回值

javascript - 将 props 传递给 react-router v4 中的路由器组件

javascript - 鼠标移动时将鼠标光标保持在 handle 上

javascript - 为什么 '+' 运算符要连接我的数字?

PHP cometd 。如何做得更好?

reactjs - Jest 测试因 gatsby webpack 配置而抛出错误

facebook - 在 ReactJS 应用程序中实现 Facebook 评论插件

javascript - React Router v4 不渲染组件