简体   繁体   English

如何在基于React函数的视图中进行api调用并在渲染中填充

[英]How to make api call and populate in render in react function based view

import React, { useState, useEffect} from 'react';

const App  = () => {
  const [setData] = useState('');

  useEffect(() => {
    fetch('https://jsonplaceholder.com/users/')
    .then(res => res.hson())
    .then(res => {
      setData(res);
    })
  });

  return ({
    setData.map(data => {
      <h1>{data.name}</h1>
    })
  });
}

Here I am making an api call in react using functional component. 在这里,我使用功能组件在响应中进行api调用。 It is coming the result. 结果来了。

But I am not able to populate result in render. 但是我无法在渲染中填充结果。 Showing map is not a function error. 显示地图不是功能错误。

Please have a look. 请看一看。

import React, { useState, useEffect} from 'react';

const App  = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch(`https://jsonplaceholder.com/users/`)
    .then(res => res.json())
    .then(res => {
      setData(res);
    })
  }, []);

  return !!data && data.map(data => <h1>{data.name}</h1>);
}

First use an array as the default value for your state 首先使用数组作为状态的默认值

Use the data variable to loop over the results 使用数据变量遍历结果

The useState hook returns 2 values, the data and the function to change that data useState挂钩返回2个值,数据和更改该数据的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 onClick function 进行 API 调用以在 React 中呈现数据列表? - How to make an API call using onClick function to render a list of data in React? 如何基于API调用呈现反应导航抽屉配置 - How to render react navigation drawer config based on API call 如何根据 API 调用中的 object 在 React Native 中渲染组件,其值根据确切的 API 调用而变化? - How do I render components in React Native based on an object from an API call whose values change depending on the exact API call? 如何在React / Jsx中的渲染器内部调用函数 - How to Call a Function inside a Render in React/Jsx 使用 React Hooks 在第二次渲染时调用 API - Make an API call on second render using React Hooks 如何在 React 中使用 UseEffect Axios API 调用填充 ToDo 列表? - How to populate ToDo list with UseEffect Axios API call in React? 如何制作回调函数来填充 textinput onChangeText 的值道具 - How to make a call back function to populate value prop of textinput onChangeText 在React模板渲染上调用函数 - Call function on React template render 在 React 中通过函数调用渲染组件 - Render Component by function Call in React 如何根据从第一次获得的值进行第二次 API 调用。 使用 React 和 useEffect 钩子 - How to Make A second API call based on the value gotten from the first. with React and useEffect hooks
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM