在 React 中渲染来自 API 的 html 响应

swa*_*is8 3 javascript reactjs

我正在尝试从 React 中的 API 渲染 html 响应。

我认为问题可能是我没有正确处理异步获取。我不确定从 BE 获取的 html 字符串是承诺还是字符串。当我在下面记录它时,我得到一个Promise

我使用这个答案中的代码dangerouslySetInnerHTML来渲染 html,尽管我不确定这是否是渲染完整页面的正确方法。backendHtmlString 是一个完整的页面,我只想将其添加到 React 中。

App.js- 渲染 html 的 React 代码:

async function createMarkup() {
  let response;
  response = await fetch(`http://localhost:8000/backed_api/html_response/?user_email=chriss%40comtura.ai`)
  const backendHtmlString = response.text()

  console.log(backendHtmlString)
  return {__html: backendHtmlString};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

function App() {
  return (
    <div className="App">
      <MyComponent/>
    </div>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

Index.js


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.
reportWebVitals();
Run Code Online (Sandbox Code Playgroud)

Shr*_*i L 5

异步函数总是返回一个Promise!确保解决它以获取数据。

请参阅:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

由于数据是从后端获取的,因此可能需要一些时间。您可以使用useEffect发出请求并设置从服务器获取的值useState

function MyComponent() {
    
      const [html, setHTML] = useState({__html: ""});
    
      useEffect(() => {
        async function createMarkup() {
          let response;
          response = await fetch(`http://localhost:8000/backed_api/html_response/?user_email=chriss%40comtura.ai`)
           const backendHtmlString = await response.text()
    
           console.log(backendHtmlString)
            return {__html: backendHtmlString};
         }
         createMarkup().then(result => setHTML(result));
      }, []);
      
    
      return <div dangerouslySetInnerHTML={html} />;
    }
Run Code Online (Sandbox Code Playgroud)

另外,看看这个场景。这可能是另一个与您类似的情况。