大家好,我有两个关于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()
未传递参数的情况下进行调用,则状态变量(array
)的初始值为undefined
。试图读取该属性length
的array
(即array.length
),那么将会给出一个错误:
const [array, setArray] = useState()
console.log(array) //=> undefined
console.log(array.length) //=> Uncaught TypeError: Cannot read property 'length' of undefined
如果调用useState([])
,即传递一个空数组作为参数,则状态变量(array
)的初始值将是一个空数组([]
)。试图读取该属性length
的array
(即array.length
),然后将做工精细:
const [array, setArray] = useState([])
console.log(array) //=> []
console.log(array.length) //=> 0
如果您以后要设置array
一个数组,并且useEffect()
确实要这样做,则将初始值设置为一个空数组是一个好习惯。然后,您可以放心地将array
其视为数组,即不必检查它是否undefined
为数组。
同样,{}
如果您的状态稍后将成为对象,则可能希望将其用作初始值。这对于防止错误很有用。例如:
const [obj, setObj] = useState()
console.log(obj) //=> undefined
console.log(obj.length) //=> Uncaught TypeError: Cannot read property 'length' of undefined
console.log(Object.entries(obj)) //=> Uncaught TypeError: Cannot convert undefined or null to object
// versus
const [obj, setObj] = useState({})
console.log(obj) //=> {}
console.log(obj.length) //=> undefined
console.log(Object.entries(obj)) //=> []
(obj.length
可能没有多大意义,但这只是一个例子。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句