如何在常量(Reactjs + JSX)中获取数据



我试图弄清楚如何让数据显示在以下内容中,但我没有成功。

我想知道我该如何放置以下内容

componentDidMount() {
const xhr = new XMLHttpRequest();
xhr.open('get', '/api-access/programs');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// set the authorization HTTP header
xhr.responseType = 'json';
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
this.setState({
Data: xhr.response.programs
});
}
});
xhr.send();
}

在下面。我基本上需要能够添加

{items.map(item => (
<ShowCard title={item.title} link={item.url} icon={item.icon}/>  
))}

到以下内容。

const Dashboard = ({ secretData, user }) => (
<div>
<Card className="container">
<CardTitle
title="Pages"
subtitle="You should get access to this page only after authentication."
/>
{secretData && <CardText style={{ fontSize: '16px', color: 'green' }}>Welcome <strong>{user.name}</strong>!<br />{secretData}</CardText>}
<Table>
<TableHeader>
<TableRow>
<TableHeaderColumn>ID</TableHeaderColumn>
<TableHeaderColumn>Page Title</TableHeaderColumn>
<TableHeaderColumn>Last Edited</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableRowColumn>1</TableRowColumn>
<TableRowColumn>John Smith</TableRowColumn>
<TableRowColumn>Employed</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>2</TableRowColumn>
<TableRowColumn>Randal White</TableRowColumn>
<TableRowColumn>Unemployed</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>3</TableRowColumn>
<TableRowColumn>Stephanie Sanders</TableRowColumn>
<TableRowColumn>Employed</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>4</TableRowColumn>
<TableRowColumn>Steve Brown</TableRowColumn>
<TableRowColumn>Employed</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>5</TableRowColumn>
<TableRowColumn>Christopher Nolan</TableRowColumn>
<TableRowColumn>Unemployed</TableRowColumn>
</TableRow>
</TableBody>
</Table>
</Card>
</div>
);
Dashboard.propTypes = {
secretData: PropTypes.string.isRequired
};
export default Dashboard;

我不太清楚您要完成什么,但我认为您正在尝试调整componentDidMount方法以在带有钩子的功能组件中工作?

如果是这样,您需要将该方法放在具有空依赖项数组的useEffect钩子中:

useEffect(() => {
const xhr = new XMLHttpRequest();
xhr.open('get', '/api-access/programs');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// set the authorization HTTP header
xhr.responseType = 'json';
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
setData(xhr.response.programs)
}
});
xhr.send();
}, [])

您还需要定义一段状态,useState来存储数据:

const [data, setData] = useState(null);

我不知道映射items与您的其他问题有何关系。这些数据来自哪里,需要在哪里?它是否与您从 get 请求中获取的数据相同?

最新更新