【问题标题】:React component default props with graphql使用 graphql 反应组件默认道具
【发布时间】:2017-09-03 02:59:35
【问题描述】:

我正在尝试从后端 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);

【问题讨论】:

  • 是的,您必须检查您的道具是否已更新为您需要的值。所以你需要检查 this.props.data.tasks.length 如果它存在那么你映射

标签: reactjs graphql react-apollo apollo-client


【解决方案1】:

是的,您必须检查查询是否已完成加载。你可以通过这个不错的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);

【讨论】:

    猜你喜欢
    • 2016-10-26
    • 2022-01-13
    • 2019-11-01
    • 2018-04-03
    • 2020-12-25
    • 2022-01-20
    • 2018-05-26
    • 2018-07-08
    • 1970-01-01
    相关资源
    最近更新 更多