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......
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…