如何解决在私有路由反应中传递道具
我正在尝试在私人路线中传递几个道具。写这个的正确方法是什么,我错过了什么?这是我的代码。我的应用程序使用此代码,因为用户能够登录并查看仪表板。然而,道具没有通过。有没有办法将 props 传递给私有路由?
<PrivateRoute exact path="/dashboard" component={Dashboard} render={routeProps =>
<Dashboard
handleUpdate={this.handleUpdate}
book={this.state.book}
info={this.state.info}
{...routeProps} />}
/>
仪表板组件
class Dashboard extends Component {
state = {
book: this.props.book,info: this.props.info,error: '',}
onlogoutClick = e => {
e.preventDefault();
this.props.logoutUser();
};
render() {
console.log(`BOOK STATE IN DB: ${this.state.book}`)
const { user } = this.props.auth;
return(
<div>
<h4>
<b>This is your page</b> {user.name}
</h4>
<button onClick={this.onlogoutClick}>logout</button>
<h2>Search Book</h2>
<Search
handleUpdate={this.props.handleUpdate}
/>
<h4>Book Results</h4>
<div>{this.state.book}</div>
</div>
);
}
}
Dashboard.propTypes = {
logoutUser: PropTypes.func.isrequired,auth: PropTypes.object.isrequired
};
const mapStatetoProps = state => ({
auth: state.auth
});
export default connect(
mapStatetoProps,{ logoutUser }
)(Dashboard);
私人路线
import React from "react";
import { Route,Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const PrivateRoute = ({ component: Component,auth,...rest }) => (
console.log(auth),<Route
{...rest}
render={props =>
auth.isAuthenticated === false ? (
<Redirect to="/login" />
) : (
<Component {...props} />
)
}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isrequired
};
const mapStatetoProps = state => ({
auth: state.auth
});
export default connect(mapStatetoProps)(PrivateRoute);
解决方法
您能否尝试移除 component={Dashboard}
道具,而仅使用渲染道具来渲染仪表板。你的代码应该是这样的
<PrivateRoute exact path="/dashboard" render={routeProps =>
<Dashboard
handleUpdate={this.handleUpdate}
book={this.state.book}
info={this.state.info}
{...routeProps} />}
/>
,
你能给我们展示一下 PrivateRouter 组件的代码吗?你可以按照这样的方式
<PrivateRoute exact path="/dashboard" component={Dashboard} props = {{book: this.state.book etc}}/>
并在 PrivateRoute 组件上接收这个 props 将其放入子组件
,来自docs
警告:<Route component>
的优先级高于 <Route render>
,所以不要在同一个 .
因此,删除 component={Dashboard}
在注释和 PrivateRoute
代码之后,我建议您将 PrivateRoute
重写为
const PrivateRoute = ({ auth,...rest }) => {
if (!auth.isAuthenticated) {
return <Redirect to="/login" />;
}
return <Route {...rest} />
);
并删除 component={Dashboard}
部分。
const PrivateRoute = ({component: Component,auth,book,handleUpdate,...rest }) => (
console.log(rest),console.log(book),<Route
{...rest}
render={props =>
auth.isAuthenticated === false ? (
<Redirect to="/login" />
) : (
<Component book={book} handleUpdate={handleUpdate} {...props} />
)
} /> )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。