Graphql查询结果返回undefined

时间:2018-04-27 20:09:59

标签: reactjs mongodb graphql next graphql-tag

我收到错误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 个答案:

答案 0 :(得分:0)

第一次使用Query操作包装的组件(如代码中)被渲染时,它会收到data道具但尚未得到结果。

data包含一个名为loading的字段。如果设置为true,则表示查询尚未收到服务器的所有结果。如果操作成功,则下次呈现组件时this.props.dataloading === falsethis.props.data.employee应具有您期望的值。

基本上,在调用this.props.data.loading之前和呈现依赖于结果的子组件之前,您应该检查truefalse还是fetchEmployees()