state
我在获取由 react-router 在具有动态段的路径上加载的组件时遇到问题/item/:id
:
var Item = React.createClass({
mixins: [State],
getInitialState: function () {
return {data: {}};
},
loadTrackData: function () {
api.getItemById(this.getParams().id, function (data) {
this.setState({data: data});
}.bind(this));
},
componentDidMount: function () {
this.loadTrackData();
},
componentWillReceiveProps: function () {
this.loadTrackData();
},
render: function () {
console.log(this.state); // empty `data` object
return (
<div>
<h2>{this.state.data.title.prop}</h2> // doesn't work
// but works with
// <h2>{this.state.data.title}</h2>
</div>
);
}
});
这些方法中的任何一个componentDidMount
都componentWillReceiveProps
不会被调用!
并渲染日志空data
对象,因为它刚刚初始化..
路由器看起来像:
var routes = (
<Route path="/" handler={Index}>
<Route name="stream" path="/item/:id" handler={Item} />
<DefaultRoute handler={Dashboard} />
</Route>
);