使用名片生成器应用程序时,尝试从地址对象(https://jsonplaceholder.typicode.com/users)中提取信息。被告知呈现文本的最佳方法是将它们放在单独的组件中,并且。现在,我很难将两个组件拼接在一起。代码在下面。 (完整的新代码集将不胜感激!)
import React, { useState, useEffect } from 'react';
const Namecard = ({ name, email, address }) => {
return (
<div>
<p>{name}</p>
<p>{email}</p>
</div>
);
};
const Address = ({ street }) => {
return <h1>{street}</h1>;
};
function App() {
const [identis, setIdenti] = useState([]);
useEffect(() => {
getIdenti();
}, []);
const getIdenti = async () => {
const acquired = await fetch(`https://jsonplaceholder.typicode.com/users`);
const data = await acquired.json();
setIdenti(data);
};
return (
<div>
{identis.map(identi => (
<Namecard name={identi.name} email={identi.email}>
<Address street={identi.address.city} />
</Namecard>
))}
</div>
);
}
export default App;
因此,使用当前代码,输出仅包含名称和电子邮件。地址对象未显示任何内容。
答案 0 :(得分:2)
Namecard
需要显式呈现其子级,否则将不呈现它们:
const Namecard = ({name,email,children}) => {
return (
<div>
<p>{name}</p>
<p>{email}</p>
{children}
</div>
)
}
答案 1 :(得分:0)
您将 Address 组件用作 Namecard 组件的子组件,因此您应告知 Namecard 组件使用该子组件并在其身体。
例如,您可以这样重写 Namecard 组件:
const Namecard = ({name, email, address, children}) => {
return (
<div>
<p>{name}</p>
<p>{email}</p>
{children}
</div>
)
};
作为子元素,我们的组件呈现<Address street={identi.address.city}/>
或者您可以这样重写:在名片中呈现 Address 组件:
const Namecard = ({name, email, address}) => {
return (
<div>
<p>{name}</p>
<p>{email}</p>
<Address street={address.city}/>
</div>
)
};
const Address = ({street}) => <h1>{street}</h1>;
function App() {
const [identis, setIdenti] = useState([]);
useEffect(() => {
getIdenti();
}, []
);
const getIdenti = async () => {
const acquired = await fetch(`https://jsonplaceholder.typicode.com/users`);
const data = await acquired.json();
setIdenti(data);
}
return (
<div>
{identis.map(identi => (
<Namecard
name={identi.name}
email={identi.email}
address={identi.address}
/>
))}
</div>
)
}