gpt4 book ai didi

reactjs - 递归数据和组件,稍后获取会抛出错误

转载 作者:行者123 更新时间:2023-12-03 13:40:28 26 4
gpt4 key购买 nike

首先关闭我的 graphql 数据模型:

type Human {
id: !String,
name: !String,
children: [Human]
}

我使用 atm 的唯一路线(中继路线配置):

class extends Relay.Route {
static queries = {
human: () => Relay.QL`query RootQuery { viewer }`
};
static routeName = 'AppHomeRoute';
}

列表组件:

class HumanList extends Component {
render() {
let {children} = this.props.human;

let subListsHTML = human ? children.map(child => (
<HumanListItem key={child.id} human={child}/>
)) : '';

return <ul>{subListsHTML}</ul>;
}
}

export default Relay.createContainer(HumanList, {
fragments: {
human: () => Relay.QL`
fragment on Human {
children {
id,
${HumanListItem.getFragment('human')}
}
}
`
}
});

列表项组件:

class HumanListItem extends Component {
state = {expanded: false};

render() {
let {human} = this.props;

let sublistHTML = '';
if (this.state.expanded) {
sublistHTML = <ul><HumanList human={human}/></ul>;
}

return (
<li>
<div onClick={this.onClickHead.bind(this)}>{human.name}</div>
{sublistHTML}
</li>
);
}

onClickHead() {
this.props.relay.setVariables({expanded: true});
this.setState({expanded: true});
}

}

HumanListItem.defaultProps = {viewer: {}};

export default Relay.createContainer(HumanListItem, {

initialVariables: {
expanded: false
},

fragments: {
human: (variables) => Relay.QL`
fragment on Human {
name,
${HumanList.getFragment('human').if(variables.expanded)}
}
`
}

});

对于根列表来说运行良好。但是,一旦我单击 ListItem 并且它展开,我就会收到以下错误:

警告:RelayContainer:预期 prop ' human' 提供的 'HumanList' 是由 Relay 获取的数据。这可能是一个错误,除非您故意传递符合此组件片段形状的模拟数据。

我无法理解它,因为我传递的数据不是模拟的,而是直接由 Relay 获取的,如 HumanList comp 中所示。

最佳答案

该错误表明 <HumanList>在数据准备好之前正在渲染。

class HumanListItem extends Component {
onClickHead() {
this.props.relay.setVariables({expanded: true});
this.setState({expanded: true}); // <-- this causes the component to re-render before data is ready
}

您可以查看变量的当前值,而不是使用状态:

class HumanListItem extends Component {
// no need for `state.expanded`

render() {
let {human} = this.props;

let sublistHTML = '';
if (this.props.relay.variables.expanded) {
// `variables` are the *currently fetched* data
// if `variables.expanded` is true, expanded data is fetched
sublistHTML = <ul><HumanList human={human}/></ul>;
}

return (
<li>
<div onClick={this.onClickHead.bind(this)}>{human.name}</div>
{sublistHTML}
</li>
);
}

onClickHead() {
this.props.relay.setVariables({expanded: true});
// no need for `setState()`
}

}

HumanListItem.defaultProps = {viewer: {}};

export default Relay.createContainer(HumanListItem, {

initialVariables: {
expanded: false
},

fragments: {
human: (variables) => Relay.QL`
fragment on Human {
name,
${HumanList.getFragment('human').if(variables.expanded)}
}
`
}

});

关于reactjs - 递归数据和组件,稍后获取会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32497759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com