Reactjs 对象在TypeScript中可能为null

Reactjs 对象在TypeScript中可能为null,reactjs,typescript,Reactjs,Typescript,使用此代码: const Products=()=>{ const classes=useStyles(); const{data}=useFetch('/categories'); 返回( {数据&& data.map((类别:CategoryInterface)=>{ 返回( ); })} ); }; 在映射之前,我在数据上得到了“Object is always null”,我尝试使用&&运算符来消除它,我还尝试将一个变量定义为CategoryInterface[],但这表明我必须首先转

使用此代码:

const Products=()=>{
const classes=useStyles();
const{data}=useFetch('/categories');
返回(
{数据&&
data.map((类别:CategoryInterface)=>{
返回(
);
})}
);
};
在映射之前,我在数据上得到了“Object is always null”,我尝试使用&&运算符来消除它,我还尝试将一个变量定义为CategoryInterface[],但这表明我必须首先转换为unknown,我应该怎么做呢

这是useFetch钩子

从'react'导入{useffect,useState};
export const useFetch=(url:string)=>{
const[state,setState]=useState({data:null,load:true});
useffect(()=>{
setState(state=>({data:state.data,load:true}));
获取(url)
.then(res=>res.json())
.then(json=>setState({data:json,load:false}));
},[url,setState]);
返回状态;
};

你的
useFetch
Hokk应该是这样的

import { useEffect, useState } from 'react';

export const useFetch = (url: string) => {
  const [state, setState] = useState({ data: {}, loading: true }); //Don't assign null to state variable

  useEffect(() => {
    setState(state => ({ data: state.data, loading: true })); //Remove this line, this is not needed 

    fetch(url)
      .then(res => res.json())
      .then(json => setState({ data: json, loading: false }));
  }, [url, setState]); //Replace [url, setState] with [] as your second argument to make useEffect work for first time.

  return state;
};
你的用法应该是

const { data } = useFetch('/categories');
{data.length>0 &&
          data.map((category: CategoryInterface) => {
            return (
              <GridListTile key={category.id}>
                <GridListTileBar title={category.name} />
              </GridListTile>
            );
          })
}
const{data}=useFetch('/categories');
{data.length>0&&
data.map((类别:CategoryInterface)=>{
返回(
);
})
}

Typescript将类型分配给JavaScript变量。大多数情况下,当您使用TS时,您应该在使用之前定义变量类型。然而,如果可能的话,TS有时可以推断变量的类型

您似乎将粘贴JS代码复制到TypeScript中,并试图使其正常工作。首先,我建议为要使用的变量定义类型,这样TS将设置正确的类型

useState
的初始调用使
state.data
类型为
null
(这是TS唯一知道它的类型)。与JS不同,TS不允许在执行期间更改类型。因此,在程序执行期间,
state.data
将具有
null
类型

const [state, setState] = useState({ data: null, loading: true });
// Type of state is
// { data: null, loading: boolean }
要纠正这一点,您应该提前提供
状态
变量的类型。它的一个可能值是
null
。另一个可能的值是从
fetch
接收的数据。您可能应该知道从
fetch
返回的数据的JSON结构类型是什么,所以请按顺序键入它

从您的代码中,我可以猜测,该数据类型可能如下所示

type IData = CategoryInterface[];
CategoryInterface
可能看起来像

interface CategoryInterface {
    id: string;
    name: string; 
}
因此,
IData
将是第二种可能的
状态类型。数据。因此,在
useState
调用期间分配
state
的类型

const [state, setState] = useState<{data: IData | null, loading: boolean}>({ data: null, loading: true });

您的数据看起来如何?它是一个数组吗?我添加了代码,它的类型为null谢谢,它确实来自一个JS项目
interface CategoryInterface {
    id: string;
    name: string;
}

type IData = CategoryInterface[];

export const useFetch = (url: string) => {
    const [state, setState] = useState<{ data: IData | null, loading: boolean }>({ data: null, loading: true });

    useEffect(() => {
        setState(state => ({ data: state.data, loading: true }));

        fetch(url)
            .then(res => res.json())
            .then(json => setState({ data: json, loading: false }));
    }, [url, setState]);

    return state;
};