我在我的应用程序中使用 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/