reactjs 如何从呈现的每个元素调用API

k5hmc34c  于 12个月前  发布在  React
关注(0)|答案(3)|浏览(109)

我想知道是否可以为每个元素渲染调用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

irtuqstp

irtuqstp1#

尝试使用react-reactive库,hope will be helpfulreact-async

idfiyjo8

idfiyjo82#

要触发这个函数,可以在组件的初始呈现过程中使用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]);

字符串

gxwragnw

gxwragnw3#

我认为一个解决办法是

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

相关问题