Reactjs 无法读取属性';地图';
我试图从一个headless CMS(Sanity.io)返回一些数据,但我的React一直遇到错误。我遵循了这一点,但现在出现了错误Reactjs 无法读取属性';地图';,reactjs,Reactjs,我试图从一个headless CMS(Sanity.io)返回一些数据,但我的React一直遇到错误。我遵循了这一点,但现在出现了错误TypeError:无法读取未定义的属性“map” 我的代码 import*as React from“React”; 从“@sanity/client”导入sanityClient; 从“reactstrap”导入{Container,Row}; const client=sanityClient({ 投射:“, 数据集:“”, useCdn:对 }); 让d
TypeError:无法读取未定义的属性“map”
我的代码
import*as React from“React”;
从“@sanity/client”导入sanityClient;
从“reactstrap”导入{Container,Row};
const client=sanityClient({
投射:“,
数据集:“”,
useCdn:对
});
让dataHenter;
const query=`*[[u type==“land”]`;
导出默认类CountryList扩展React.Component{
建造师(道具){
超级(道具);
此.state={
国家:[]
};
}
静态异步getInitialProps(){
返回{
国家/地区:等待客户端。获取(查询)
};
}
render(){
const{country}=this.props;
返回(
{country.map(country=>(
-
{country.image}
{country.name}
))}
);
}
}
你知道我做错了什么吗 在呈现组件时,国家/地区可能未定义或为空。确保它在初始渲染时为数组:
const { country } = this.props || { country: [] };
或者
const { country } = this.props;
您可以将地图与国家一起使用,如下所示:
{country && country.length && country.map(country => (
这将确保仅在有国家的情况下运行map。在itI上使用country.map()函数时,确保“country”是一个数组。我通过将常量切换为“const{country=[]}=This.props”来运行它;它是我从Sanity.io获取的数组。但是没有显示任何内容,因此映射仍然失败
{country && country.length && country.map(country => (