3
我試圖從後端graphql服務提取記錄,並使用Array.map函數呈現它們。不幸的是,在他們被加載之前,我得到錯誤,因爲他們沒有定義我試圖在組件上設置默認道具,但它沒有奏效。我是否必須檢查一切是否已加載,或者是否有特定方法將默認值注入這些道具。我的代碼看起來像那樣React組件默認道具與graphql
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,如果它存在,然後你映射 –