首页 > 解决方案 > 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;
    }
};

标签: reactjsreact-pdf

解决方案


由于您的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 });
    });
}

推荐阅读