React新手求助:无法渲染GitHub API用户数据,遇React子元素错误
Hey there! Let's fix up your React code step by step—you're really close, just a few small issues tripping you up.
1. The Core Error: Invalid React Child
Your main error ("Objects are not valid as a React child") comes from how you're trying to render the user's email and bio. Writing {user.email, user.bio} in JSX uses the comma operator, which only returns the last value (user.bio) here. Worse, if either value is undefined (common if a GitHub user hasn't set their email/bio), React can throw confusing errors about invalid children.
Fix it by explicitly rendering each field, and handle empty values to keep the UI clean:
<p key={user.login}> Email: {user.email || 'No email provided'} <br /> Bio: {user.bio || 'No bio available'} </p>
2. Missing this Binding
Class component methods don't automatically bind this to the component instance. When your form submits, this inside getUser will be undefined, which would break this.setState once you fix the first error.
Pick one of these fixes:
- Use an arrow function for the method: This auto-binds
thisgetUser = async (e) => { // Your existing code here } - Bind in the constructor:
constructor(props) { super(props); this.state = { users: [] }; this.getUser = this.getUser.bind(this); }
3. Broken API Request URL
You used & (HTML escape code) in your fetch URL instead of a plain &. GitHub's API will misinterpret this, leading to failed requests.
Fix the URL:
const profileResponse = await fetch(`https://api.github.com/users/${username}?client_id=${client_id}&client_secret=${client_secret}`);
Full Fixed Code
Here's the complete working version:
import React, { Component } from 'react'; class App extends Component { state = { users: [] } getUser = async (e) => { e.preventDefault(); const username = e.target.elements.username.value; const profileResponse = await fetch(`https://api.github.com/users/${username}?client_id=${client_id}&client_secret=${client_secret}`); const user = await profileResponse.json(); this.setState({ users: this.state.users.concat([user]) }); } render() { return ( <div className="App"> <h1>Search users</h1> <p>Enter a username to fetch a user.</p> <form onSubmit={this.getUser}> <input type="text" name="username" placeholder="GitHub username" /> <button>Find User</button> </form> { this.state.users.length > 0 && this.state.users.map((user) => ( <p key={user.login}> Email: {user.email || 'No email provided'} <br /> Bio: {user.bio || 'No bio available'} </p> )) } </div> ); } } export default App;
内容的提问来源于stack exchange,提问作者masterPenguin

