我想知道当Apollo <Query>组件完成加载时,设置父组件状态的最佳方式是什么?我有一个id,有时我必须查询它。我想知道处理这件事的最好方法是什么?
现在我有了它,其中的子组件将监听prop的变化,如果我注意到我正在寻找的数据的prop发生了变化,我会调用一个函数来更新状态。
有没有一种更好的方法来处理这个问题,而不需要子组件监听更新?
这是我目前正在做的伪代码
import * as React from 'react';
import { Query } from 'react-apollo';
class FolderFetcher extends React.Component<Props, { id: ?string}> {
constructor(props) {
super(props);
this.state = {
id: props.id
}
}
setId = (id) => {
this.setState({ id });
};
render() {
const { id } = this.props;
return (
<Query skip={...} query={...}>
((data) => {
<ChildComponent id={id} newId={data.id} setId={this.setId} />
})
</Query>
);
}
}
class ChildComponent extends React.Component<Props> {
componentDidUpdate(prevProps) {
if (prevProps.newId !== this.props.newId &&
this.props.id !== this.props.newId) {
this.props.setId(this.props.newId);
}
}
render() {
...
}
}发布于 2018-04-04 00:30:16
您可以从apollo中导出子组件作为与HoC封装的组件
import { graphql } from 'react-apollo'
class ChildComponent extends React.Component {
// inside props you have now handy `this.props.data` where you can check for `this.props.data.loading == true | false`, initially it's true, so when you will assert for false you have check if the loading was finished.
}
export default graphql(Query)(ChildComponent)另一种选择是手动获取客户端,然后运行client.query(),它将返回promise,您可以为then()方法链接。
https://stackoverflow.com/questions/49633933
复制相似问题