不知道这是React.js错误还是Javascript语言的“功能”。我有一个名为Page
的React.js(编辑:使用v0.12.x)组件,它充当路由器并根据路由选择子组件。我创建了一个mixin,它添加了一个名为runRoute
的函数,该函数带有一个JSX组件,并使用Page
的setState
方法来更新state.routeComponent
。此外,runRoute
还调用forceUpdate()
以确保重新呈现Page
。
问题在于,当两个组件属于同一类时,它们似乎无法区分两个组件的状态。我会解释。
我有两个子组件,分别称为Board
和Profile
。 Board
被重新用于不同的上下文。如果运行两个都使用<Board/>
的连续路线,则React.js不会更新UI。仅当使用其他类(例如<Profile/>
)的连续路由真正更新UI时。并且,如果状态更改为使用<Board/>
的其他路由,它将仅将UI更新为<Board/>
的适当状态。
以下是<Page/>
和我的Router
mixin的一些示例代码:
Router.js
module.exports = function(){
return {
getInitialState: function () {
return {
routeComponent: null
};
},
runRoute: function(component){
this.setState({routeComponent: component});
this.forceUpdate();
},
componentWillMount: function() {
var self = this;
self.router = Router(self.routes).configure({
resource: self,
notFound: self.notFound
});
self.router.init();
}
};
}
Page.jsx
module.exports = function(React, Router, NotFound, Profile, Board) {
return React.createClass({
mixins: [Router],
routes: {
'/board': 'trending',
'/board/mostloved': 'mostLoved',
'/profile': 'profile'
},
trending: function() {
this.runRoute(
<Board title="Trending Boards" setTitle={this.props.setTitle} />
);
},
mostLoved: function() {
this.runRoute(
<Board title="Loved Boards" setTitle={this.props.setTitle} />
);
},
profile: function() {
this.runRoute(
<Profile setTitle={this.props.setTitle} />
);
},
notFound: function () {
this.runRoute(
<NotFound setTitle={this.props.setTitle} />
);
},
render: function() {
return this.state.routeComponent;
}
});
};
感谢是否有人对此有所了解。谢谢!
最佳答案
如果不查看Board
组件就无法确定,但问题似乎在于其状态取决于属性,并且属性更新时(在runRoute
之后)您不会保持它们同步。
这是演示问题的简单示例(jsfiddle):
var Board = React.createClass({
getInitialState: function() {
return {title: this.props.title}
},
render: function() {
return <h1>{this.state.title}</h1>
}
});
var Page = React.createClass({
getInitialState: function () {
return {routeComponent: null}
},
handleClick: function(title) {
var self = this;
return function() {
self.setState({ routeComponent: <Board title={title} /> })
}
},
render: function() {
return <div>
<a href='#' onClick={this.handleClick('Trending')}>Trending</a>
<br/>
<a href='#' onClick={this.handleClick('Most Loved')}>Most Loved</a>
{this.state.routeComponent}
</div>;
}
});
单击链接会更改
Page
的状态,但不会更改Board
的外观。您需要通过处理
Board
中的更改来保持componentWillReceiveProps
的状态与其更新的属性同步。只需在
Board
中添加几行即可解决此问题: componentWillReceiveProps: function(props) {
this.setState({title: props.title})
},
附带说明:您不必在
this.forceUpdate()
之后立即使用this.setState()
。如果没有它就无法获得必要的行为,则说明您做错了事。