将Meteor 1.3中的某些代码切换为ES6 + React语法。组件需要获取流星数据,因此我正在使用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, startDate: { $gte: start }, endDate: { $lte: end } }).fetch(), } }, Component);
由于尝试访问状态,因此出现错误“无法获取undefined的currentMonth”。有什么建议?
您可以将旧组件分为两个部分:一个包含状态并处理事件的部分,另一个仅显示结果的部分。确保将事件处理程序作为回调传递给子组件。还要注意父组件如何使用createContainer()函数的返回值。
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);