我在我的应用中使用了react和backbone模型。为了彼此沟通,我使用更高阶的组件(https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750)。react + backbone + react-router,提取模型
让说我有一个骨架模型:
class Item extends Backbone.Model {
defaults() {
return {
id: null,
name: 'item',
subItems: [],
link: null
};
}
// This is sample API response to GET /item/1
{
id: 1,
name: 'item1',
link: '/item/1',
subItems: [{
id: 2,
name: 'item2',
link: '/item/2',
subItems: []
}, {
id: 3,
name: 'item3',
link: '/item/3',
subItems: []
}]
}
// This is sample API response to GET /item/2
{
id: 2,
name: 'item2',
link: '/item/2',
subItems: []
}
}
和反应成分:
class ItemComponent extends React.Component {
constructor(props, context) {
super(props, context);
}
onClickLink(link, e) {
e.preventDefault();
this.context.router.transitionTo(link);
}
render() {
const itemData = this.props.data.toJSON();
const itemNodes = itemData.map(function(item) {
return (
<li><a href='' onClick={this.onClickLink.bind(this, item.link)}>{item.name}</a></li>
);
});
return (
<div>
<span>{itemData.name}</span>
<ul>{itemNodes}</ul>
</div>
);
}
}
ItemComponent.contextTypes = {
router: React.PropTypes.func.isRequired
};
,我有我的高阶组件
const item = new Item();
const NewComponent = connectToModel(ItemComponent, item);
其中
function connectToModel(Component, model) {
class ComponentConnection extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
data: model
};
}
componentDidMount() {
model.on('add remove change', this.onModelChange.bind(this));
}
componentWillUnmount() {
model.off(null, null, this.onModelChange.bind(this));
}
onModelChange() {
this.setState({
data: model
});
}
render() {
return (
<Component
{...this.state}
{...this.props}
/>
);
}
}
}
条
我的路线:
const Routes = (
<Route handler={App} path="/">
<Route name="item" path="item/:id" handler={Item} />
</Route>
);
我的问题:
我如何可以调用API,当用户请求的URL
/item/1
所以不是const item = new Item();
我会打电话像const item = new Item({id: 1});
渲染之前获取数据。当一个子项目用户点击,反应路由器将让他e.g
/item/2
,但再怎么我可以告诉我的反应组件,该航线PARAM也因此改变获取新的模式覆盖我目前的一个并呈现新的数据。