React沙箱应用报错:无法重声明'response'及API适配问题求助
问题解决方案
1. 按钮无响应问题
按钮未绑定点击事件,点击后无法触发数据加载逻辑,需给按钮添加onClick属性:
<button onClick={loadUsers}>Load Data</button>
2. API数据结构不匹配导致map报错
https://reqres.in/api/users?page=1的返回结构是包含data字段的对象,而非直接的用户数组,且用户字段为first_name、last_name、avatar,和你代码中使用的login、avatar_url不匹配:
- 修改
setUsers的赋值逻辑,取响应中的data数组:
setUsers(jsonresponse.data);
- 调整map中的解构字段,匹配API返回的真实字段:
{users.map(({ id, first_name, last_name, avatar }) => ( <li key={id}> Name: {first_name} {last_name} <img src={avatar} alt={`${first_name} ${last_name}`} style={{ width: '50px', marginLeft: '10px' }} /> </li> ))}
3. "Cannot redeclare block-scoped variable 'response'" 错误
该错误是沙箱环境中全局存在同名response变量,和局部变量冲突。解决方式:
- 给局部变量重命名,比如改为
fetchResponse - 或者用块级作用域包裹内部代码,隔离变量:
const loadUsers = async () => { console.log("before"); { const response = await fetch("https://reqres.in/api/users?page=1"); const jsonresponse = await response.json(); setUsers(jsonresponse.data); } };
修改后的完整代码
import React, { useState } from "react"; import "./styles.css"; const App = () => { const [users, setUsers] = useState([]); const loadUsers = async () => { console.log("before"); const fetchResponse = await fetch("https://reqres.in/api/users?page=1"); const jsonResponse = await fetchResponse.json(); setUsers(jsonResponse.data); }; return ( <div className="App"> <h1>Hello All</h1> <button onClick={loadUsers}>Load Data</button> <h2>Users:</h2> <ul> {users.map(({ id, first_name, last_name, avatar }) => ( <li key={id} style={{ display: 'flex', alignItems: 'center', margin: '10px 0' }}> Name: {first_name} {last_name} <img src={avatar} alt={`${first_name} ${last_name}`} style={{ width: '50px', marginLeft: '10px' }} /> </li> ))} </ul> </div> ); }; export default App;
内容的提问来源于stack exchange,提问作者Maya Elfeky
相关产品推荐
相关产品推荐

