reactjs - ReactJS:获取响应不返回到 componentDidMount;无法加载 PDF
问题描述
在 ReactJS 中,组件在收到 Fetch 响应后不会重新渲染。所以总是在屏幕上看到“正在加载 PDF...”消息
componentDidMount 代码如下,
componentDidMount() {
const {getData} = this.props;
let data = getData();
console.log(data) // printed empty while fetch in progress
this.setState({pdfData : data})
console.log(this.state.pdfData) // printed empty while fetch in progress
}
获取后,不会打印 getData 值(数据)。pdfData 未设置,因为此组件未重新渲染。同时,在getData()中打印出数组值。
使用 react-pdf 库将返回的数据呈现为 pdf
render() {
return(
<div style={{ width: 500 }}>
<Document
file={this.state.pdfData }
onLoadSuccess={() => console.log("Success")}
onLoadError = {(error) => console.log(error.message)}
>
<Page pageNumber={1} />
</Document>
</div>
);
}
getData 在下面给出,
export const getData = id => async (dispatch) => {
let response;
try {
response = API_CALL
console.log(response) // PDF raw data printed
let rawLength = response.length;
let array = new Uint8Array(new ArrayBuffer(rawLength));
for (let i=0; i < rawLength; i++){
array[i] = response.charCodeAt(i);
}
console.log(array); //array value printed
return array;
} catch (error) {
dispatch(setError(error.message));
throw error;
}
};
解决方案
由于您的getData
函数是async
,您将需要await
结果 componentDidMount
或按承诺行事(假设您已经await
在调用 API)。例如:
等待:
async componentDidMount() {
const { getData } = this.props;
let data = await getData(); // <-- Await the async here
this.setState({ pdfData: data });
}
或承诺:
componentDidMount() {
const { getData } = this.props;
getData().then((data) => { // <-- Act on the promise result
this.setState({ pdfData: data });
});
}
推荐阅读
- origen-sdk - 在 Flow.create {} 中调用接口
- python - Dockerfile python无法打开文件
- django - 如何在 Django 中为整个页面创建类似管理员的外观?
- java - 如何仅记录部分异常?
- google-apps-script - 如何创建记录开始和结束时间数据的脚本
- javascript - 得到承诺的总和
- mysql - 将值与 JSON_EXTRACT 进行比较
- python - 恢复MacOS系统Python3版本
- mysql - 无法从 MYSQL 工作台打开我的jawsDb
- javascript - 在Angular中选中或取消选中时,如何在每个复选框下显示或隐藏div标签?