我正在嘗試學習鈎子,該useState方法使我感到困惑。我正在將初始值分配給數組形式的狀態。useState即使使用spread(...)或,in中的set方法對我也不起作用without spread operator。我在另一台PC上創建了一個API,該API正在調用並獲取要設置為狀態的數據。
這是我的代碼:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{
category: "",
photo: "",
description: "",
id: 0,
name: "",
rating: 0
}
];
const [movies, setMovies] = useState(initialValue);
useEffect(() => {
(async function() {
try {
//const response = await fetch(
//`http://192.168.1.164:5000/movies/display`
//);
//const json = await response.json();
//const result = json.data.result;
const result = [
{
category: "cat1",
description: "desc1",
id: "1546514491119",
name: "randomname2",
photo: null,
rating: "3"
},
{
category: "cat2",
description: "desc1",
id: "1546837819818",
name: "randomname1",
rating: "5"
}
];
console.log(result);
setMovies(result);
console.log(movies);
} catch (e) {
console.error(e);
}
})();
}, []);
return <p>hello</p>;
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
setMovies(result)以及setMovies(...result)不工作。可以在這里使用一些幫助。
我希望將結果變量推入movies數組中。
