ebr*_*art 12 javascript meteor reactjs
将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() {
...
}
});
Run Code Online (Sandbox Code Playgroud)
新法典迄今为止
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);
Run Code Online (Sandbox Code Playgroud)
获取错误"无法获取undefined的currentMonth",因为它正在尝试访问状态.有什么建议?
aed*_*edm 24
您可以将旧组件拆分为两个部分组件:一个用于保存状态并处理事件,另一个仅显示结果.确保将事件处理程序作为回调传递给子组件.另请注意父组件如何使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2432 次 |
| 最近记录: |