我正在从 JS 代码中触发 XHR。这个阻止渲染的 XHR 在每次页面加载时都会触发,所以我想在页面生命周期的早期与 JS 和 CSS 资源并行获取它。在 my 中index.html,我将添加以下代码:
<head>
<link rel="stylesheet" href="style.css">
<link rel="preload" as="fetch" href="/xhr-to-be-fetched-early">
</head>
Run Code Online (Sandbox Code Playgroud)
XHR 请求需要一些自定义标头,例如authorization& Accept。有什么方法可以将这些标题添加到link标签中,无论是在 HTML 本身内部还是通过 JS?或者不可能缓存这样的请求?
我正在http://localhost:3001/api/cards从组件的componentDidMount函数向我的API发出GET请求,因此只有在第一次呈现组件之后才会发出api请求(如反应官方指南所示).
此API设置数组的状态data.在render函数中,我调用data.mapfunction来从这个数组中渲染多个组件.我该如何测试是否已呈现所需数量的组件?
我的组件:
//CardGrid.js
import React from 'react';
import { Card, Col, Row } from 'antd';
import 'antd/dist/antd.css';
import { parseJSON } from './commonfunction';
import './CardGrid.css';
export default class extends React.Component {
constructor()
{
super();
this.state = {
data: {},
};
}
fetchData = async () => {
try
{
const data = await parseJSON(await fetch('http://localhost:3001/api/cards'));
console.log('data');
console.log(data);
this.setState({ data });
}
catch (e)
{
console.log('error is: ');
console.log(e);
}
}
componentDidMount() {
this.fetchData(); …Run Code Online (Sandbox Code Playgroud)