javascript - 在私有路由 React 中传递道具
问题描述
我正在尝试在私人路线中传递几个道具。写这个的正确方法是什么,我错过了什么?这是我的代码。我的应用程序使用此代码,因为用户能够登录并查看仪表板。但是,道具并没有通过。有没有办法将道具传递到私人路线?
<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);
解决方案
你能告诉我们 PrivateRouter 组件的代码吗?你可以按照这样的方式
<PrivateRoute exact path="/dashboard" component={Dashboard} props = {{book: this.state.book etc}}/>
并在 PrivateRoute 组件上接收此道具以将其放入子组件
推荐阅读
- node.js - Nest JS 中间件 .exclude 选项不会阻止排除路由的中间件
- reactjs - react(或者一般来说可能是es6)是否允许别名导出?
- java - Pi4J 类路径错误 - Intellij 在 Pi 零 W 上远程运行
- java - 如何查找 Android Studio 2020.3.1 的 Firebase UI 依赖项
- java - SonarQube 抛出“用固定值替换随机生成的值”。测试方法
- php - Laravel 8 - 在 null 上调用成员函数 getRealPath()
- python - Selenium webdriver firefox dosent 更新后工作
- firebase - firebase + audio_service:当应用程序终止时,应用程序在推送通知后卡在启动画面
- java - 安卓导航组件
- reactjs - 在 React js react-router-dom V6 中实现嵌套路由