[英]The difference between using useState with [] and without it, and also with {}
Hey guys I have two questions about the react.js hook.嘿伙计们,我有两个关于 react.js 钩子的问题。 Please help.
请帮忙。 Get confused a few days:(
纠结了几天:(
1.What is the difference between using [] and without [] in the useState() 1.useState()中使用[]和不使用[]有什么区别
I noticed that when using useState([]) the console.log(array) will be like我注意到当使用useState([])时,console.log(array) 会像
(100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
However when I use useState() in my code it will look like the following, and I couldn't use array.length there will be an error saying "cannot read property length of undefined"但是,当我在代码中使用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.Also, when do we use {} in useState({})? 2.另外,我们什么时候在useState({})中使用{}? I do know that {} is for object.Please give some examples:(
我知道 {} 用于 object。请举一些例子:(
Following is the main code App.js:以下是 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;
If you call useState()
without passing an argument, the initial value of the state variable ( array
) will be undefined
.如果您在不传递参数的情况下调用
useState()
,则 state 变量( array
)的初始值将是undefined
。 Trying to read the property length
of array
(ie array.length
) will then give an error:尝试读取
array
的属性length
(即array.length
)会报错:
const [array, setArray] = useState()
console.log(array) //=> undefined
console.log(array.length) //=> Uncaught TypeError: Cannot read property 'length' of undefined
If you call useState([])
, ie you pass an empty array as the argument, the initial value of the state variable ( array
) will be an empty array ( []
).如果调用
useState([])
,即传递一个空数组作为参数,则 state 变量 ( array
) 的初始值将是一个空数组 ( []
)。 Trying to read the property length
of array
(ie array.length
) will then work fine:尝试读取
array
的属性length
(即array.length
)将正常工作:
const [array, setArray] = useState([])
console.log(array) //=> []
console.log(array.length) //=> 0
If you are going to set array
to an array later – and you are, in the useEffect()
– it's a good practice to set the initial value to an empty array.如果您打算稍后将
array
设置为一个数组 - 而您是在useEffect()
中 - 将初始值设置为一个空数组是一个很好的做法。 Then you can safely treat array
like it's an array, ie you don't have to check if it's undefined
or an array.然后您可以安全地将
array
视为数组,即您不必检查它是undefined
的还是数组。
Similarly, you might want to use {}
as the initial value if your state is later going to be an object.同样,如果您的 state 稍后将成为 object,您可能希望使用
{}
作为初始值。 This can be useful to prevent errors.这对于防止错误很有用。 For example:
例如:
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
probably doesn't make much sense, but it's just an example.) (
obj.length
可能没有多大意义,但这只是一个例子。)
Square brackets []
will create an Array object and while using curly brackets {}
creates a plain object .方括号
[]
将创建一个数组 object ,而使用花括号{}
创建一个普通的 object 。 it's really a matter of how you would like to be able to access the data.这实际上是您希望如何访问数据的问题。 you can even set argument to
useState('')
.您甚至可以将参数设置为
useState('')
。 Without using initial value useState()
it will be undefined
不使用初始值
useState()
它将是undefined
的
Arrays only hold values: Arrays 仅保存值:
const numbers = [2, 3, 4, 5, 35]
const myNumbers = numbers .map(item=> {
return item* 2
})
Output
[ 4, 6, 8, 10, 70 ]
array Objects have key-value pairs.数组对象具有键值对。 Mostly we use whenever we want to create and store a list of multiple items in a single variable
大多数情况下,每当我们想在单个变量中创建和存储多个项目的列表时,我们都会使用
const products = [
{ id: '1', name: 'Foo' },
{ id: '2', name: 'bar' }
];
const myProducts = products.map((item, key) => {
return (
<tr key={key}>
<td>{item.id}</td>
<td>{item.name}</td>
</tr>
);
});
furthermore, if you iterate data using map() {}
this give you Unhandled Rejection (TypeError): products.map is not a function as it is plain object.此外,如果您使用map()
{}
迭代数据,这会给您未处理的拒绝(TypeError): products.map 不是 function因为它是普通的 ZA8CFDE6331BD59EB2AC96F8911C4B66
const [products, setProducts] = useState({});
products.map((item) => {
return item; })
by using const [products, setProducts] = useState([]);
通过使用
const [products, setProducts] = useState([]);
you will get products.length
= 0 without error.你会得到
products.length
= 0没有错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.