GraphQL查询结果undefined,Next.js中privateKey读取报错求助
Let's walk through each of your problems and fix them step by step:
1. this.props.employee Returns Undefined + componentWillMount Concerns
First off, componentWillMount is deprecated in React 16.3+ — it’s not recommended for data-fetching or accessing async props like GraphQL results anymore.
The core reason this.props.data.employee is undefined is that GraphQL queries are asynchronous. When your component first mounts, the data hasn’t finished loading yet. If you’re using Apollo Client’s graphql HOC (a common setup for Next.js + GraphQL), your props.data will include a loading flag that tells you when the query is complete.
Fix:
- Replace
componentWillMountwithcomponentDidMount(the standard lifecycle method for post-mount data operations) - Always check the
loadingstate before accessing your data:
componentDidMount() { if (!this.props.data.loading) { this.fetchEmployees(); } } // If you ever switch to functional components (highly recommended!), use useEffect instead: // useEffect(() => { // if (!data.loading && data.employee) { // fetchEmployees(); // } // }, [data]);
2. Uncaught (in promise) TypeError: Cannot read property 'privateKey' of undefined
This error pops up because you’re trying to access privateKey on an undefined value — meaning this.props.data.employee hasn’t loaded yet when your fetchEmployees function runs.
Fix:
Add a guard clause to ensure employee exists before accessing its properties. You can use optional chaining (?.) for concise checks, or explicit if statements:
fetchEmployees = async () => { // Guard clause to avoid undefined errors if (!this.props.data?.employee) { console.warn("Employee data hasn't loaded yet"); return; } // Now safely access privateKey const privateKey = this.props.data.employee.privateKey; this.setState({ privateKey }); // Rest of your fetch logic... };
Bonus: Improve UX with Loading/Error States
To avoid confusion and make your component more robust, render loading/error states while the GraphQL query runs:
render() { const { data } = this.props; if (data.loading) { return <div>Loading employee data...</div>; } if (data.error) { return <div>Error loading employee data: {data.error.message}</div>; } // Render your table once data is ready return ( <table> {/* Your table content using data.employee */} </table> ); }
内容的提问来源于stack exchange,提问作者madsmosu

