我遇到了一个从未有过的奇怪问题。
我正在使用Material UI组件,特别是CardActionArea
与
Redirect
中的react-router-dom
点击CardActionArea
后,我想将用户重定向到他们刚刚单击的组件的详细信息屏幕。
详细视图有时呈现,而有时不呈现。例如,如果我单击CardActionArea
,则不会渲染详细视图 ,但是,如果我直接导航到URL,则将渲染详细视图 。
这是相关的代码:
// Dashboard.js
return (
<Grid container spacing={40} className={classes.root}>
<TopMenu></TopMenu>
<Router>
<Route exact path="/dashboard/v/:videoId" component={VideoDetail} />
</Router>
<Router>
<Route exact path="/dashboard" component={(YouTubeVideoGallery)} />
</Router>
</Grid>
);
CardActionArea在这里:
constructor(props) {
super(props);
this.state = {
redirect: false
};
this.handleCardActionClick = this.handleCardActionClick.bind(this);
}
handleCardActionClick = () => {
this.setState({redirect: true});
}
render() {
const { classes } = this.props;
const date = moment(this.props.video.publishedAt);
if (this.state.redirect) {
return (<Redirect to={`/dashboard/v/${this.props.video.id}`} />)
}
return (
<Card className={classes.card}>
<CardActionArea onClick={this.handleCardActionClick}>
<CardHeader
title={
(this.props.video.title.length > 21) ?
this.props.video.title.substr(0, 18) + '...' :
this.props.video.title
}
subheader={`${date.format('MMMM DD[,] YYYY')} - Views: ${this.props.video.viewCount}`}
/>
<CardMedia
className={classes.media}
image={this.props.video.thumbnails.medium.url}
title={this.props.video.title}
/>
</CardActionArea>
</Card>
);
}
我不确定是什么问题。
答案 0 :(得分:0)
第一件事handleCardActionClick是一个箭头函数,因此您无需在构造函数中进行绑定。可以删除
要重定向onclick,请执行以下操作
render(){
const url = `/dashboard/v/${this.props.video.id}`;
return(
<div>
{this.state.redirect && <Redirect to={url} />}
</div>
)
}