【发布时间】:2016-09-30 23:01:43
【问题描述】:
我有一个名为 MainContainer 的反应类,它显示一些内容。它有一个孩子SidebarContainer,列出了一堆链接。如果 URL 中没有参数值,我会渲染我的主容器并默认使用默认 ID 1 作为后备加载第一条内容:
var MainContainer = React.createClass({
getInitialState: function() {
return {
selectedContent: this.props.params.slug || 1
},
componentWillReceiveProps: function(nextProps, nextState) {
this.setState({
selectedContent: this.props.params.slug || 1
});
},
}
SidebarContainer 组件有一个链接选择器:
<Link to={content.slug}>
{content.title}
</Link>
当我点击链接时,浏览器的 URL 明显改变,但没有其他反应。当我再次单击时,会呈现正确的内容。但是,当我复制粘贴带有指定参数的 url 时,它会第一次呈现正确的内容。
我的 ReactDOM 渲染方法具有以下 react-router 配置:
ReactDOM.render((
<Router>
<Route path="/" component={MainContainer}/>
<Route path="/content/:slug" component={MainContainer}/>
</Router>
), document.getElementById('react-app'));
我是否错误地使用了componentWillReceiveProps 生命周期方法?
【问题讨论】:
标签: javascript reactjs react-router