我正在尝试从后端graphql服务获取记录并使用Array.map函数呈现它们。不幸的是,在它们加载之前我得到了错误,因为它们未定义。我试图在组件上设置默认道具,但它不起作用。我是否必须检查是否所有内容都已加载,或者是否有特定方法将默认值注入这些道具中。我的代码现在看起来像
import React from 'react';
import { graphql } from 'react-apollo';
import { fetchTasks } from '../../../graphql/tasks';
import { Dashboard } from '../components/Dashboard';
const propTypes = {
data: React.PropTypes.shape({
tasks: React.PropTypes.array
})
};
const defaultProps = {
data: {
tasks: []
}
};
class DashboardContainer extends React.Component {
render() {
const titles = this.props.data.tasks.map(task => task.title);
return(
<Dashboard
titles={titles}
/>
);
}
}
DashboardContainer.propTypes = propTypes;
DashboardContainer.defaultProps = defaultProps;
export default graphql(fetchTasks)(DashboardContainer);
答案 0 :(得分:2)
是的,您必须检查查询是否已完成加载。你可以通过这个很好的tutorial,在那里你建立一个口袋妖怪应用程序。该链接指向它们显示基本查询的部分以及如何检查它是否已加载。
在您的情况下,它可能如下所示:
import React from 'react';
import { graphql } from 'react-apollo';
import { fetchTasks } from '../../../graphql/tasks';
import { Dashboard } from '../components/Dashboard';
const propTypes = {
data: React.PropTypes.shape({
tasks: React.PropTypes.array
})
};
const defaultProps = {
data: {
tasks: []
}
};
class DashboardContainer extends React.Component {
render() {
if (this.props.data.loading) {
return <div > Loading < /div>;
}
const titles = this.props.data.tasks.map(task => task.title);
return ( <
Dashboard titles = {
titles
}
/>
);
}
}
DashboardContainer.propTypes = propTypes;
DashboardContainer.defaultProps = defaultProps;
export default graphql(fetchTasks)(DashboardContainer);
&#13;