【问题标题】:ReactJS : Fetch response not returning to componentDidMount; Failed to load PDFReactJS:获取响应不返回到 componentDidMount;无法加载 PDF
【发布时间】:2019-05-04 23:10:29
【问题描述】:

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

【问题讨论】:

    标签: reactjs react-pdf


    【解决方案1】:

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

    【讨论】:

    • @user3362908 乐于助人!如果此答案已解决您的问题,请点击绿色复选标记将其标记为已接受。
    猜你喜欢
    • 2019-07-30
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    相关资源
    最近更新 更多