在 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;
}
};