Graphql 查询结果返回 undefined
Posted
技术标签:
【中文标题】Graphql 查询结果返回 undefined【英文标题】:Graphql query result comes back undefined 【发布时间】:2018-10-08 17:25:06 【问题描述】:我收到错误Uncaught (in promise) TypeError: Cannot read property 'privateKey' of undefined
在尝试 console.log this.props.employee
时返回未定义的员工查询结果
我正在使用 Graphql 和 Next.js。我不确定 componentWillMount 是否是正确的生命周期方法,因为 this.props.data.employee
是 undefined
。
class EmployeeTable extends Component
state =
employeesList: [],
privateKey: ""
fetchEmployees = async () =>
console.log(this.props.data.employee);
console.log(this.props.data.employee.privateKey);
const adminWallet = new ethers.Wallet(this.state.privateKey, provider);
const EmployeeStore = new ethers.Contract(address, abi, adminWallet);
let count;
await EmployeeStore.functions.employeesCount().then(function(value)
count = value;
);
let employeesList = [];
for(let i = 1; i<=count; i++)
await EmployeeStore.getEmployeeByIndex(i).then(function(result)
employeesList.push(result);
);
;
console.log(employeesList);
return employeesList;
;
componentWillMount = async () =>
var employees = await this.fetchEmployees();
this.setState(employeesList: employees);
;
renderRows()
return this.state.employeesList.map((employee, index) =>
return (<EmployeeRow
key=index
employee=employee
/>
);
);
;
render()
const Header, Row, HeaderCell, Body = Table;
return(
<div>
<h3>Employees</h3>
<Table>
<Header>
<Row>
<HeaderCell>Name</HeaderCell>
<HeaderCell>Employee ID</HeaderCell>
<HeaderCell>Address</HeaderCell>
<HeaderCell>Authenticated</HeaderCell>
</Row>
</Header>
<Body>this.renderRows()</Body>
</Table>
</div>
)
const employee = gql`
query employee($employeeID: String)
employee(employeeID: $employeeID)
privateKey
`;
export default graphql(employee,
options:
variables: employeeID: "1234"
,
)
(EmployeeTable);
【问题讨论】:
【参考方案1】:第一次使用 Query 操作包装的组件(例如在您的代码中)被渲染时,它会收到 data
属性,但还没有结果。
data
包含一个名为 loading
的字段。如果设置为true
,则表示查询尚未从服务器接收到所有结果。如果操作成功,下次渲染组件时this.props.data
将具有loading === false
并且this.props.data.employee
应该具有您期望的值。
基本上,在调用fetchEmployees()
之前和渲染依赖结果的子组件之前,您应该检查this.props.data.loading
是true
还是false
。
【讨论】:
以上是关于Graphql 查询结果返回 undefined的主要内容,如果未能解决你的问题,请参考以下文章