在Meteor 1.3中切换一些代码到ES6 React语法.组件需要获取Meteor数据,所以我使用一个createComponent来替换getMeteorData().问题是,旧的getMeteorData使用了组件的状态,该组件不被createContainer组件访问.
旧代码:
Component = React.createClass({ mixins: [ReactMeteorData],getMeteorData() { var mo = this.state.currentMonth; var start = newDate(moment(mo).startOf('month')); return { events: collections.events.find({ $or: qwry,startDate: { $gte: start },endDate: { $lte: end } }).fetch(),} },render() { ... } });
如此远的新代码
class Component = React.Component { constructor(props) { super(props); } render() { ... } } export default createContainer(({params}) => { var mo = this.state.currentMonth; var start = newDate(moment(mo).startOf('month')); return { events: collections.events.find({ $or: qwry,endDate: { $lte: end } }).fetch(),} },Component);
解决方法
您可以将旧组件拆分为两个部分组件:一个保存状态并处理事件的组件,以及仅显示结果的纯组件.确保将事件处理程序作为回调传递给子组件.还要注意,父组件如何使用createContainer()函数的返回值.
// Parent component,setState should go here export default class StateHolder extends React.Component { constructor(params) { super(params); this.state = {myKey: 1}; } incrementKey() { this.setState({myKey: this.state.myKey + 1}); } render() { return <Container myKey={this.state.myKey} onClick={this.incrementKey.bind(this)} />; } } // Child component,renders only class PureComponent extends React.Component { render() { return <div> {this.props.myValue} <button onClick={this.props.onClick}>click me</button> </div>; } } // Decorated child container. // Make sure to use this one in parent component's render() function! let Container = createContainer((props) => { let doc = MyCollection.findOne({someKey: props.myKey}); return { myValue: doc ? doc.someValue : null } },PureComponent);