useState()返回未定义的,我不知道为什么

时间:2020-03-18 08:07:12

标签: reactjs react-hooks

谁能告诉我为什么console.log语句返回undefined。我意识到如果它是从API获取数据的,那么这是不确定的,但数据位于其上方?

const Slider = () => {
  const movies = {
    1: {
      title: "first title",
      image: "first image",
      url: "first url"
    },
    2: {
      title: "second title",
      image: "second image",
      url: "second url"
    },
    3: {
      title: "third title",
      image: "third image",
      url: "third url"
    },
    4: {
      title: "third title",
      image: "thirs image",
      url: "third url"
    }
  }

  const [ currentMovie, setMovie ] = useState(movies[0])
  const [ active, setActive ] = useState(0)
  console.log(currentMovie)
}

1 个答案:

答案 0 :(得分:3)

在这里,您使用的是JavaScript对象,而不是数组,并且没有0的键。 因此,确实,movie [0]的结果是不确定的