admin管理员组文章数量:1417061
Hey guys I have two questions about the react.js hook. Please help. Get confused a few days :(
1.What is the difference between using [] and without [] in the useState()
I noticed that when using useState([]) the console.log(array) will be like
(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"
Array(100)
0: {id: "181913649", name: "Drake Hotline Bling", url: ".jpg", width: 1200, height: 1200, …}
1: {id: "112126428", name: "Distracted Boyfriend", url: ".jpg", width: 1200, height: 800, …}
2: {id: "87743020", name: "Two Buttons", url: "...
.
.
2.Also, when do we use {} in useState({}) ? I do know that {} is for object.Please give some examples :(
Following is the main code App.js:
function App() {
const [array,setarray]=useState([])
useEffect(()=>{
fetch(";)
.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;
Hey guys I have two questions about the react.js hook. Please help. Get confused a few days :(
1.What is the difference between using [] and without [] in the useState()
I noticed that when using useState([]) the console.log(array) will be like
(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"
Array(100)
0: {id: "181913649", name: "Drake Hotline Bling", url: "https://i.imgflip./30b1gx.jpg", width: 1200, height: 1200, …}
1: {id: "112126428", name: "Distracted Boyfriend", url: "https://i.imgflip./1ur9b0.jpg", width: 1200, height: 800, …}
2: {id: "87743020", name: "Two Buttons", url: "https://i.imgflip./1...
.
.
2.Also, when do we use {} in useState({}) ? I do know that {} is for object.Please give some examples :(
Following is the main code App.js:
function App() {
const [array,setarray]=useState([])
useEffect(()=>{
fetch("https://api.imgflip./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;
Share
Improve this question
edited Feb 27, 2021 at 5:56
skyboyer
23.8k7 gold badges62 silver badges71 bronze badges
asked Feb 26, 2021 at 13:54
Yan SkywalkerYan Skywalker
1192 silver badges12 bronze badges
2
-
1
The
useState
function is a React hook, whose argument sets the initial value of the state created. If you pass an array, it will be an array, if you pass an object, it'll be an object, etc. If you don't pass anything, thenundefined
will be used. – FZs Commented Feb 26, 2021 at 14:14 -
1
The output of
console.log
is pretty much irrelevant. The argument you pass touseState
is the initial value. Which value to use depends on which value you want the state to have, and what other code expects the value to be. I assumememes
is an array, so initializing it to an empty array seems to be the right thing. Also look at what valueControl
expects to get fordata
. – Felix Kling Commented Feb 26, 2021 at 14:15
2 Answers
Reset to default 6If you call useState()
without passing an argument, the initial value of the state variable (array
) will be undefined
. Trying to read the property length
of array
(i.e. array.length
) will then give an error:
const [array, setArray] = useState()
console.log(array) //=> undefined
console.log(array.length) //=> Uncaught TypeError: Cannot read property 'length' of undefined
If you call useState([])
, i.e. you pass an empty array as the argument, the initial value of the state variable (array
) will be an empty array ([]
). Trying to read the property length
of array
(i.e. array.length
) will then work fine:
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. Then you can safely treat array
like it's an array, i.e. you don't have to check if it's undefined
or an array.
Similarly, you might want to use {}
as the initial value if your state is later going to be an 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.)
Square brackets []
will create an Array object and while using curly brackets {}
creates a plain 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('')
. Without using initial value useState()
it will be undefined
Arrays only hold values:
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.
const [products, setProducts] = useState({});
products.map((item) => {
return item; })
by using const [products, setProducts] = useState([]);
you will get products.length
= 0 without error.
本文标签:
版权声明:本文标题:javascript - The difference between using useState with [] and without it, and also with {} - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745259689a2650299.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论