如何处理需要子组件状态的Meteor数据
How to handle Meteor Data that requires state from child component?
将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,
startDate: { $gte: start },
endDate: { $lte: end }
}).fetch(),
}
}, Component);
获取错误"cannot get currentMonth of undefined",因为它正在尝试访问状态。有什么建议吗?
您可以将旧组件拆分为两个部分组件:一个保存状态并处理事件,另一个仅显示结果。请确保将事件处理程序作为回调传递给子组件。还要注意父组件如何使用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);
相关文章:
- 从组件状态的数组中删除元素
- Reactjs:在修改对象之前,是否需要复制处于组件状态的对象
- 在Redux中使用组件状态是反模式的吗
- 如何处理需要子组件状态的Meteor数据
- 单击按钮更改组件状态
- 当登录状态为组件状态时,如何使用react路由器实现依赖登录的路径
- 我是否必须在 React 中使用 this.state 来维护组件状态
- 如何使用react路由器将顶级组件状态传递给Routes
- React组件状态与道具动态输入
- 在子组件之间共享父组件状态'州
- 当父组件状态改变时,如何强制子组件重新呈现
- 有条件地绑定组件状态
- js:创建一个多选择组件.选项组件状态的组合流不输出改变的状态
- 从props中初始化组件状态
- 为什么不将redux存储状态存储在本地组件状态中呢?
- 将Facebook Web SDK与ReactJS组件状态集成
- 当从父组件状态传递时,React prop没有在正确的时间更新
- 如何将包含组件'状态的值传递回父组件
- 检查事件函数中的组件状态是否有效
- 当值被分配给组件状态时,为什么console.log打印之前的状态