我遇到了一个我以前从未遇到过的奇怪问题。
我正在使用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>
);
}
我不确定问题是什么。
第一件事handleCardActionClick是一个箭头函数,所以你不需要在构造函数中进行绑定。这可以删除
要重定向onclick,请执行以下操作
render(){
const url = `/dashboard/v/${this.props.video.id}`;
return(
<div>
{this.state.redirect && <Redirect to={url} />}
</div>
)
}