javascript - 如何使用 React 延迟加载远程数据

标签 javascript reactjs fetch

我对 React 还很陌生,我正在尝试延迟加载存储在服务器上的 markdown 文件。

我尝试设置一个异步箭头函数来获取文件并通过标记运行它。 我在这里找到了这个演示 https://codesandbox.io/s/7zx3jlrry1我尝试过遵循它,但还没有弄清楚如何遵循它。

class Markdown extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            // some state
        }
    }

    render() {
        let markdown = React.lazy(async () => {
            // fetch the file
            const response = await fetch(path)
            if (!response.ok) {
                return (<p>Response was not ok</p>)
            } else {
                // if successful, return markdown
                let blob = await response.blob()
                return marked(blob)
            }
        })
        return  (
            <React.Suspense fallback={<div class="markdown">Loading</div>}>
                <div class="markdown" id={this.props.id} dangerouslySetInnerHTML={{__html: markdown}} />
            </React.Suspense>
        )
    }
}

当我尝试调试它时,箭头函数实际上并未执行,div 的内部 HTML 是“[object Object]”。 任何有关我如何实现这一目标的帮助将不胜感激。

最佳答案

你得到[object Object]在你的html中因为dangerouslySetInnerHTML需要一个返回对象 {__html: '<div>some html string</div>'} 的函数。除此之外,您没有使用推荐的通过网络请求获取数据的方式。请继续阅读以获取有关如何执行任务的更多详细信息。

React Suspense用于延迟加载Components不用于获取数据,如 react 文档所述:

In the future we plan to let Suspense handle more scenarios such as data fetching.

React.Suspense lets you specify the loading indicator in case some components in the tree below it are not yet ready to render. Today, lazy loading components is the only use case supported by :

在这种情况下您不需要延迟加载。使用 react 生命周期方法来执行诸如在正确的时间获取数据之类的事情。这里你需要的是react-lifecylce方法componentDidMount 。您也可以使用 component state操纵渲染的内容和未渲染的内容。例如,您可以显示 error occuredloading通过设置变量。

class Markdown extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			loading: true,
			error: false,
			html: ""
		}
	}

	componentDidMount = () => {
		this.fetchMarkdown()
	}

	fetchMarkdown = async () => {
		const response = await fetch(path)
		if (!response.ok) {
			// if failed set loading to false and error to true
			this.setState({ loading: false, error: true })
		} else {
			// If successful set the state html = markdown from response
			let blob = await response.text()
			this.setState({ loading: false, html: blob })
		}
	}

	getMarkup = () => {
		return { __html: this.state.html }
	}

	render() {
		if (this.state.error) {
			return <div>Error loading markup...</div>
		}
		else if (this.state.loading){
			return <div>Loading...</div>
		} 
		else {
			return <div class="markdown" id={this.props.id} dangerouslySetInnerHTML={this.getMarkup()} />
		}
	}
}

关于javascript - 如何使用 React 延迟加载远程数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58470562/

相关文章:

javascript - 为什么我的简单 Ember.js Handlebars 助手在异步加载数据时不起作用?

reactjs - 如何运行 React 应用程序的构建?

javascript - Flux + React.js - Action 中的回调是好是坏?

javascript - 如果 fetch 中 boolean 为 false 如何跳过 next .then() ?

javascript - 受污染的 Canvas ,由于 CORS 和 SVG?

javascript - 如何从另一个js文件中获取变量值

javascript - 函数无法正确读取状态值

javascript - 如何格式化从 Object.values 中获取的 JSON 数据字符串?

javascript - 无法从 fetch PUT 访问 Express 服务器的正文数据

javascript - React Redux Fetch 操作返回 "415 (Unsupported Media Type)"和 "401 (unauthorized)"