我有一个事件组件,它显示数据库中所有事件的列表。
一般来说,我对授权和响应/ redux比较陌生 而且我不知道如何正确进行授权。
我希望每个人都能一直看到所有事件 以及当您单击它时,您会看到可用于该特定事件的票证(现在它显示了所有事件的所有票证,稍后我将不得不对其进行修复)
但是我想要的主要事情现在已经发生
是 访客未登录时,“ CREATE EVENT”按钮不会显示 或显示出来,但是当访客点击它时 他们还没有登录 他们被重定向到/ login页面
import React, { PureComponent } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { getAllEvents, getEvent, addEvent } from "../../actions/events";
import { getUsers } from '../../actions/users'
import Paper from "@material-ui/core/Paper";
import Moment from "moment";
import { Redirect } from "react-router-dom";
class EventsList extends PureComponent {
componentWillMount() {
this.props.getAllEvents();
}
getEvent(eventId) {
this.props.getEvent(eventId);
}
addEvent = event => {
this.props.addEvent(event);
};
render() {
const { events, authenticated } = this.props;
const eventsList = events.sort((a, b) =>{
return a.id - b.id;
});
if (!authenticated) return <Redirect to="/login" />;
return (
<div>
<Paper className="styles" elevation={4}>
<h1>Coming Events</h1>
<table>
<thead>
<tr>
<th>Event Name</th>
<th>Starts</th>
<th>Ends</th>
</tr>
</thead>
<tbody>
{eventsList.map(event => (
<tr key={event.id}>
<td>
{" "}
<Link
className="link"
to={`/events/${event.id}`}
onClick={() => this.getEvent(event.id)}
>
{event.name}
</Link>
</td>
<td style={{border:"2px solid black"}}> {Moment(event.startDate).format('ll')}</td>
<td style={{ border: "2px solid black" }}> {Moment(event.endDate).format('ll')}</td>
<td />
</tr>
))}
</tbody>
</table>
<br />
<br />
<Link className="link" to={`/createEvent`}>
CREATE EVENT
</Link>
</Paper>
</div>
);
}
}
const mapStateToProps = function(state) {
console.log('users', state.users)
return {
events: state.events,
event: state.event,
authenticated: state.currentUser !== null,
users: state.users === null ? null : state.users
};
};
export default connect(
mapStateToProps,
{
getAllEvents,
getEvent,
addEvent,
getUsers
}
)(EventsList);
任何建议
答案 0 :(得分:1)
好吧,要隐藏按钮,您可以像这样
{ if(this.props.authenticated) {
<Link className="link" to={`/createEvent`}>
CREATE EVENT
</Link>
}}
要根据用户的身份验证进行重定向,可以使用Link
的onClick事件(我不确定Link
组件是否公开了onClick事件,如果没有,将其更改为常规按钮。
<Link className="link" onClick={this.onCreateEvent}> // maybe use a <button /> instead
CREATE EVENT
</Link>
// ...
onCreateEvent() {
if(this.props.authorized) this.props.history.push("/createEvent"); // this dependes on which version of React-Router you are using.
else this.props.history.push("/login");
}