results.map 不是函数(考虑在树中添加错误边界以自定义错误处理行为。)
对于更有经验的开发人员来说,这似乎是一个简单的问题,但它已经让我恼火了很长一段时间。
我一直让 .map 不是一个函数,尽管它显然是。看下面的代码
我正在迭代结果状态,但它似乎不起作用
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<App.js>>>>>>>>>>>>>> >>>>>>>>>>>>>>
import "./App.css";
import React, { useEffect, useState } from "react";
import ContactCard from "./ContactCard";
const App = () => {
const [results, setResults] = useState([]);
useEffect(() => {
fetch("https://randomuser.me/api/?results=5")
.then((response) => response.json())
.then((data) => {
console.log(data);
setResults(data);
});
}, []);
return (
<div>
{results.map((result, i) => {
return (
<ContactCard
key={i}
avatarUrl={result.picture.large}
name={result.name}
email={result.email}
age={result.dob.age}
/>
);
})}
</div>
);
};
export default App;
展开片段
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>> >>
import React, { useState } from "react";
const ContactCard = (props) => {
const [showAge, setShowAge] = useState(false);
const showAgefn=()=>{
setShowAge(!showAge)
}
return (
<div className="contact-card">
<img src={props.avatarUrl} alt="profile" />
<div className="user-details">
<p>Name: {props.name}</p>
<p>Email: {props.email}</p>
<button onClick={showAgefn}>Show age</button>
{showAge && <p>Age: {props.age}</p>}
</div>
</div>
);
};
export default ContactCard;