简体   繁体   English

React Hooks - useState 初始化成为对象的空数组?

[英]React Hooks - useState initializes empty array that becomes object?

In the following code, I believe I am initializing gameList as an empty array.在下面的代码中,我相信我将 gameList 初始化为一个空数组。 The first console.log shows gameList is an empty array.第一个 console.log 显示 gameList 是一个空数组。 I then use a console.log in useEffect() that displays gameList as an object but I do not believe that I am doing anything to transform gameList.然后我在 useEffect() 中使用 console.log 将 gameList 显示为一个对象,但我不相信我正在做任何事情来转换 gameList。 Can anyone explain this?谁能解释一下? I was trying to pass an array of objects to a child component but even upon using Object.values() on the gameList "object" it is still returning as an object.我试图将一组对象传递给子组件,但即使在游戏列表“对象”上使用 Object.values() 它仍然作为对象返回。 Thanks!谢谢!

Edit : Perhaps the way I should've has asked this is: "Why does gameList show up in child component as an object with gameList as property? Why does it not arrive in the GameList component as an empty array called gameList? This is happening before submitting my form by the way.编辑:也许我应该问这个问题的方式是:“为什么 gameList 作为一个对象出现在子组件中,而 gameList 作为属性?为什么它没有作为一个名为 gameList 的空数组到达 GameList 组件中?这正在发生在顺便提交我的表格之前。

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import GameList from './GameList';

const Searchbar = () => {
  const [searchString, setSearchString] = useState('');
  const [gameList, setGameList] = useState([]);

  console.log(gameList); // []

  useEffect(() => {
    console.log('gameList is ' + typeof gameList); // gameList is object
  });

  const requestGames = searchString => {
    axios
      .get(`http://localhost:3001/game/${searchString}`)
      .then(({ data }) => setGameList(data))
      .catch(e => console.log(e));
  };

  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault();
          requestGames(searchString);
        }}
      >
        <label htmlFor="search-string">Search</label>
        <input
          type="text"
          placeholder="search.."
          onChange={e => setSearchString(e.target.value)}
        />
      </form>
      <GameList gameList={gameList} />
    </div>
  );
};

export default Searchbar;

Arrays have type object in JavaScript:数组在 JavaScript 中具有类型object

 console.log(typeof []) //=> "object"

You can read more about the typeof operator on MDN [1].您可以在 MDN [1] 上阅读有关typeof运算符的更多信息。

To check if something is an array you can do this:要检查某个东西是否是一个数组,您可以这样做:

 console.log(Array.isArray([])) //=> true

Or this:或这个:

 console.log(Object.prototype.toString.call([])) //=> "[object Array]"

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM