ReactJS:获取响应不返回 componentDidMount;无法加载 PDF

ReactJS : Fetch response not returning to componentDidMount; Failed to load PDF

在 ReactJS 中,组件在收到 Fetch 响应后不会重新渲染。所以总是在屏幕上看到 "Loading 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
    }

fetch后,getData值(data)没有打印出来。未设置 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 });
    });
}