【发布时间】:2021-02-26 13:54:41
【问题描述】:
大家好,我有两个关于 react.js 钩子的问题。请帮忙。迷茫了几天:(
1.useState()中使用[]和不使用[]有什么区别
我注意到当使用 useState([]) 时,console.log(array) 会像
(100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
但是,当我在代码中使用 useState() 时,它将如下所示,并且我无法使用 array.length 会出现错误提示 “无法读取未定义的属性长度”
Array(100)
0: {id: "181913649", name: "Drake Hotline Bling", url: "https://i.imgflip.com/30b1gx.jpg", width: 1200, height: 1200, …}
1: {id: "112126428", name: "Distracted Boyfriend", url: "https://i.imgflip.com/1ur9b0.jpg", width: 1200, height: 800, …}
2: {id: "87743020", name: "Two Buttons", url: "https://i.imgflip.com/1...
.
.
2.另外,我们什么时候在 useState({}) 中使用 {} ?我知道 {} 是对象。请举一些例子:(
以下是App.js的主要代码:
function App() {
const [array,setarray]=useState([])
useEffect(()=>{
fetch("https://api.imgflip.com/get_memes")
.then(response => response.json())
.then(response => {
const {memes} = response.data
console.log(memes[0].url)
setarray(memes)
})
},[])
console.log(array)
console.log(array[0])
console.log(array.length)
return (
<div>
<Header />
<Control data={array}/>
</div>
);
}
export default App;
【问题讨论】:
-
useState函数是一个 React 钩子,它的参数设置创建状态的初始值。如果你传递一个数组,它将是一个数组,如果你传递一个对象,它将是一个对象,等等。如果你不传递任何东西,那么将使用undefined。 -
console.log的输出几乎无关紧要。您传递给useState的参数是初始值。使用哪个值取决于您希望状态具有哪个值,以及其他代码期望该值是什么。我假设memes是一个数组,因此将其初始化为一个空数组似乎是正确的。还要查看Control期望为data获得什么价值。
标签: javascript reactjs ecmascript-6 react-hooks