Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

javascript - How to use useState hook to map JSON response from API

My API returns complex json like these.

[ 
 {id: 1, pub_date: "2021-01-06T20:24:57.547721Z"},
 {id: 2, pub_date: "2021-01-06T20:24:57.547721Z"},
 {id: 3, pub_date: "2021-01-06T20:24:57.547721Z"}
]

So my trial is like this

const [result, setResult] = useState({});
const [result, setResult] = useState(null);
const [result, setResult] = useState([]);

useEffect(() => {
  axios.get('http://localhost:8000/api/results/')
  .then(res=>{
    console.log(res.data); // correctly received
    setResult(res.data); // error
    console.log(result); // nothing appears
  })
  .catch(err=>{console.log(err);});
}, []);

However for any try, it shows the error like

Error: Objects are not valid as a React child (found: object with keys {id, pub_date}). If you meant to render a collection of children, use an array instead.


I have some trial and errors.

There is still difficult behaiver to understand.

  const [cnt,setCnt] = useState(0);

  useEffect(() => {
    axios.get('http://localhost:8000/api/results/')
  
    .then((res)=> {
 
      setCnt(2);
      console.log(cnt);//shows 0

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

why setCnt is not workd?? I am more confused......


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are calling setResult(res.data), then your result state should be of type [].

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

const fetchData = () =>
  Promise.resolve({
    data: [
      { id: 1, pub_date: "2021-01-06T20:24:57.547721Z" },
      { id: 2, pub_date: "2021-01-06T20:24:57.547721Z" },
      { id: 3, pub_date: "2021-01-06T20:24:57.547721Z" }
    ]
  });

const ListItem = ({ id, pub_date }) => (
  <li>
    {id} &mdash; {pub_date}
  </li>
);

const ListItems = ({ items }) => (
  <ul>
    {items.map((props) => (
      <ListItem key={props.id} {...props} />
    ))}
  </ul>
);

const App = () => {
  const [result, setResult] = useState([]);

  useEffect(() => {
    fetchData().then((res) => {
      setResult(res.data);
    });
  }, []);

  return (
    <div className="App">
      <ListItems items={result} />
    </div>
  );
};

export default App;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...