我想知道是否可以為每個元素渲染呼叫 api。下面的代碼對我不起作用。
export default function App() {
const items = [
{ title: 1, description: "description1" },
{ title: 2, description: "description2" }
];
const finalTitleByApi = async (title) => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${title}`
).then((response) => response.json());
return response;
};
return (
<div>
{items.map((item) => {
return (
<p>
{finalTitleByApi(item.title).title}
</p>
);
})}
</div>
);
}
上面的代碼有什么問題。任何幫助將不勝感激。謝謝你。
這是示例代碼框鏈接https://codesandbox.io/s/for-each-rendered-element-that-c ??alls-api-pmcnn6?file=/src/App.js:879-886
uj5u.com熱心網友回復:
嘗試使用react-async庫,hope will be helpful react-async
uj5u.com熱心網友回復:
要觸發異步函式useEffect,請在組件的初始渲染期間呼叫它,如下所示。此外,您也可以使用狀態來管理它。
const [responseState, setResponseState] = useState(null);
const finalTitleByApi = async () => {
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
).then((response) => response.json());
console.log("Response: ", response);
setResponseState(response);
};
useEffect(() => {
finalTitleByApi();
}, []);
useEffect(() => {
console.log("Response State: ", responseState);
}, [responseState]);
uj5u.com熱心網友回復:
我認為的一種解決方案是
import React, { useEffect } from "react";
import "./styles.css";
import {useApplicationContext} from './Context';
export default function App() {
const {titles, setTitles} = useApplicationContext();
const items = [
{ title: "1", description: "description1" },
{ title: "5", description: "description2" },
{ title: "8", description: "description2" },
{ title: "9", description: "description2" },
{ title: "10", description: "description2" },
{ title: "24", description: "description2" }
];
const makeDivs = () => {
let a = {};
items.map(async (item) => {
const res = await fetch(
`https://jsonplaceholder.typicode.com/todos/${item.title}`
).then(response => response.json());
a[item.title] = res.title;
setTitles((prevState) => {
return {...a}
});
})
}
React.useEffect(()=> {
makeDivs()
}, [])
// console.log(a )
return (
<div>
{JSON.stringify(titles)}
{items.map((item, index) => {
return (
<p
key={Math.random()}
style={{
color: "black",
backgroundColor: "yellow",
height: 400,
width: 400
}}
>
<span>index: {item.title} {titles && titles[item.title]}</span>
</p>
);
})}
</div>
);
}
用于不重新渲染沙箱的組件狀態 鏈接的背景關系提供程式是沙箱
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471676.html
