我想知道是否可以为每个元素渲染调用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>
);
}
上面的代码有什么问题?任何帮助将不胜感激。
这是示例codesandbox链接https://codesandbox.io/s/for-each-rendered-element-that-calls-api-pmcnn6?file=/src/App.js:879-886
要触发异步函数,请使用
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]);
我认为的一个解决方案是
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>
);
}
使用上下文提供程序不重新渲染组件状态 沙盒的链接是Sandbox