簡體   English   中英

用graphql反應組件默認道具

[英]React component default props with graphql

我正在嘗試從后端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);

是的,您必須檢查查詢是否已完成加載。 你可以通過這個很好的教程 ,在那里你建立一個口袋妖怪應用程序。 該鏈接指向它們顯示基本查詢的部分以及如何檢查它是否已加載。

在你的情況下,它可能看起來像這樣:

 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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM