[英]Asynchronously map JSX in React
I have async function that basically fetches a list from the backend, and I would create a html list on the FE with those elements.我有异步 function ,它基本上从后端获取一个列表,我会在 FE 上用这些元素创建一个 html 列表。 For that I want to do a map on that list.
为此,我想在该列表中执行 map。 The problem is that since it's the result of a async function, it seems that I need add some details.
问题是,由于它是异步 function 的结果,看来我需要添加一些细节。
Based on my searches , I should do something similar to this:根据我的搜索,我应该做类似的事情:
const listItems = await Promises.all( podcastList.map(
(podcast) =>{
<ListItem value = {podcast} />}
));
However, I get the error:但是,我收到错误:
Compiled with problems:X
ERROR in ./src/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected reserved word 'await'. (21:20)
The remaining functions are:剩下的功能是:
function ListItem(props) {
return <li>{props.value}</li>;
}
async function podcast_list() {
let podcast_list;
const headers = { 'Content-Type': 'application/json' };
const res = await fetch('/list_podcasts', { method: 'GET',headers});
podcast_list = await res.json();
console.log(podcast_list);
return podcast_list
}
podcastList = podcast_list();
JSX can't be returned from a component asynchronously. JSX 不能从组件异步返回。 Separate your raw data from your JSX--
await
the request for the raw data, set state to trigger a rerender once the data arrives, then build the JSX UI.将原始数据与 JSX 分开——
await
原始数据的请求,设置 state 以在数据到达后触发重新渲染,然后构建 JSX UI。
const {useEffect, useState} = React; // Mock for demonstration fetch = () => Promise.resolve({ json: () => Promise.resolve([ "some podcast", "some other podcast", ]) }); // const ListItem = ({value}) => ( <li key={value}>{value}</li> ); const Podcasts = () => { const [podcasts, setPodcasts] = useState([]); useEffect(() => { fetch("/list_podcasts").then(res => res.json()).then(data => { setPodcasts(data); }); }, []); return ( <div> {podcasts.length? ( <ul> {podcasts.map(e => <ListItem value={e} />)} </ul> ): <div>Loading...</div> } </div> ); }; ReactDOM.render(<Podcasts />, document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="root"></div>
Use camelCase
in JavaScript, not snake_case
and don't forget to add a unique key
attribute to list items.在 JavaScript 中使用
camelCase
,而不是snake_case
,并且不要忘记为列表项添加唯一key
属性。
You don't need to await on maps when rendering JSX elements.渲染 JSX 元素时,您无需在地图上等待。 Just:
只是:
const listItems = podcastList.map((podcast) => <ListItem value={podcast} />)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.