javascript React / NextJS -这怎么可能是一个“无法读取null的属性”错误?

hzbexzde  于 2022-12-02  发布在  Java
关注(0)|答案(2)|浏览(149)

I have a NextJS application which conditionally renders a set of data tables using useState and useEffect:

const [board,setBoard] = useState("AllTime");

const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false);
const [TrendingCreatorLeaderboardVisible, setTrendingCreatorLeaderboardVisible] = useState(false);
const [TrendingVideoLeaderboardVisible, setTrendingVideoLeaderboardVisible ] = useState(false)

useEffect(() => {
  board === "AllTime"
    ? setAllTimeLeaderboardVisible(true)
    : setAllTimeLeaderboardVisible(false);
  board === "TrendingVideo" ? setTrendingCreatorLeaderboardVisible(true) : setTrendingCreatorLeaderboardVisible(false);
  board === "TrendingCreator" ? setTrendingVideoLeaderboardVisible(true) : setTrendingVideoLeaderboardVisible(false);
}, [board]);

const handleOnChange = (e: { target: { value: SetStateAction<string>; }; }) => {
  setBoard(e.target.value);
};

The tables visibility is then controlled through a dropdown element:

<select id ="dropdown" value={board} onChange={handleOnChange} className="mb-5 rounded-full bg-black px-6 py-3 duration-100 ease-in hover:bg-white hover:fill-black hover:text-black w-80 text-3xl tracking-tight font-work">
    <option value="AllTime">All Time</option>
    <option value="TrendingVideo">Trending Video</option>
    <option value="TrendingCreator">Trending Creator</option>
</select>

{AllTimeLeaderboardVisible && <AllTimeLeaderboard />}
{TrendingVideoLeaderboardVisible && <TrendingVideoLeaderboard />}
{TrendingCreatorLeaderboardVisible && <TrendingVideoLeaderboard />}

While I have set „AllTime" as the first option Value, NextJS is giving me a

TypeError: Cannot read properties of null (reading 'useState')

Error which is pointing to:

const [board,setBoard] = useState('AllTime');

How can this be a property of null?

vxbzzdmp

vxbzzdmp1#

检查是否正确导入useState,例如

import { useState } from 'react';

如果这不能解决问题,请查看similar SO question下的注解,该注解指出这是一个配置问题。

kupeojn6

kupeojn62#

我的错误是在进行无效的钩子调用时,没有在函数组件的主体内调用函数。

相关问题