【发布时间】:2019-06-20 10:38:32
【问题描述】:
所以我正在使用 react-router 开发一个 react 应用程序。我在更改路线时遇到问题,更改反映在 URL 中,但安装的组件没有更改。这是组件,它是我的主要容器组件之一:
class AppContent extends Component {
state = {
isStarted: false
};
componentDidMount = async () => {
try {
await this.props.checkIsScanning();
this.setState({ isStarted: true });
}
catch (ex) {
this.props.showErrorAlert(ex.message);
}
};
componentWillUpdate(nextProps) {
if (nextProps.history.location.pathname !== '/' && !nextProps.isScanning) {
this.props.history.push('/');
}
}
render() {
return (
<div>
<VideoNavbar />
{
this.state.isStarted &&
<Container>
<Row>
<Col xs={{ size: 8, offset: 2 }}>
<Alert />
</Col>
</Row>
<Switch>
<Route
path="/scanning"
exact
render={ (props) => (
<Scanning
{ ...props }
isScanning={ this.props.isScanning }
checkIsScanning={ this.props.checkIsScanning }
/>
) }
/>
<Route path="/"
exact
render={ (props) => (
<VideoListLayout
{ ...props }
isScanning={ this.props.isScanning }
/>
) }
/>
</Switch>
</Container>
}
</div>
);
}
}
const mapStateToProps = (state) => ({
isScanning: state.scanning.isScanning
});
const mapDispatchToProps = (dispatch) => bindActionCreators({
checkIsScanning,
showErrorAlert
}, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(AppContent));
所以,让我们专注于重要的事情。有一个 redux 属性 isScanning,它对这里的行为至关重要。默认情况下,当我打开应用程序时,路由是“/”,并且 VideoListLayout 组件正常显示。从那里,我单击一个按钮开始扫描,这会将路径更改为“/scanning”,并显示扫描组件。除其他外,扫描组件会定期调用服务器以检查扫描是否完成。完成后,它将“isScanning”设置为 false。当 AppContent 重新渲染时,如果 "isScanning" 为 false,它会将 "/" 推送到历史记录中以将用户送回主页。
这里几乎所有的东西都能正常工作。扫描组件在我开始扫描时出现,它轮询服务器就好了。扫描完成后,redux 已正确更新,因此“isScanning”现在为 false。 AppContent 中的 componentWillUpdate() 函数正常工作,它成功地将“/”推送到历史记录中。 URL从“/scanning”变成了“/”,所以路由正在改变。
但是,Scanning 组件仍然挂载,而 VideoListLayout 组件未挂载。我一生都无法弄清楚为什么会这样。我会认为一旦路线改变,组件也会改变。
我确定我在这里做错了什么,但我不知道那是什么。帮助将不胜感激。
【问题讨论】:
标签: javascript reactjs react-router