简体   繁体   English

使用 react useState 将 api 响应存储到数组

[英]Store api response to an array using react useState

I am new to react hooks.我是反应钩子的新手。 I am trying to cast API response into an array using react useState hook.我正在尝试使用 react useState钩子将 API 响应转换为数组。 It's giving me empty with the below approach以下方法让我感到空虚

const [post, setPostArray] = useState([]);

useEffect(() => {
  const postparams = { userList: result };
  axios
    .get(environment._urlPosts, { headers, params: postparams })
    .then(posts => {
      // storing response data in array
      setPostArray(posts.data.post);

      console.log(post);
    })
    .catch(err => {});
}, []);

Then I used the below approach and I was able to see data is printing in the console log然后我使用了下面的方法,我能够在控制台日志中看到数据正在打印

axios.get(environment._urlPosts, { headers, params: postparams }).then(posts => {
  // storing response data in array
  for (let obj of posts.data.post) {
      post.push(obj)
  }
  setPostArray(post)
  console.log(post)

But when I try to iterate this post array in my JSX, it's giving me empty array.但是当我尝试在我的 JSX 中迭代这个 post 数组时,它给了我一个空数组。

  </div>
{/* array length */}
        {post.length}

        {post.map(post =>
            <div className="card">
                <Post username={post.username} fullname={post.fullname} postedTime={post.postedTime} postContent='Hi' tweeterLike={post.tweeterLike} />
            </div>
        )}

Can you please help me to resolve this?你能帮我解决这个问题吗?

Here is a minimal Example of what you are trying to achieve.这是您要实现的目标的最小示例。 This is the working code:这是工作代码:

import React, {useEffect, useState} from "react";
import "./styles.css";

export default function App() {
  const [post, setPostArray] = useState([])

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => {
      console.log(json);
      setPostArray([json]);
  })
    //  setPostArray([{name: 'a'}, {name: 'b'},{name: 'c'}])
},[])

console.log(post)
  return (
    <div className="App">
      {
        post.map(item => <div>{item.title} </div>)
      }
    </div>
  );
}

Here is the link to the example in codeSandBox : https://codesandbox.io/s/jovial-snow-773kp这是 codeSandBox 中示例的链接https : //codesandbox.io/s/jovial-snow-773kp

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM