gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:44:22 25 4
gpt4 key购买 nike

我对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com