我正在 React
中构建一个小型调查组件,用户可以在其中决定是否在不同的选择中投票。通过 Airtable
我遇到的问题是我在终端中收到一个错误,名为:TypeError: 无法读取未定义的属性“名称”
这似乎与具有 0 个值的未定义值有关。但是我是 'map()' 那个特定的数组并且不明白它是什么未定义:
survey.js
const Survey = () => {
const [items, setItems] = React.useState([]);
const [loading, setLoading] = useState(true);
const getRecords = async () => {
const records = await base('Survey').select({}).firstPage().catch(err => console.log(err));
// console.log(records);
const newRecords = records.map((record) => {
// lets destructure to get the id and fields
const {id, fields} = record;
return {id, fields};
})
setItems(newRecords);
setLoading(false);
}
useEffect(() => {
getRecords();
console.log(items)
},[])
return (
<Wrapper className="section">
<div className="container">
<Title title="Survey" />
<h3>most important room in the house?</h3>
{loading ? (
<h3>loading...</h3>
) : (
<ul>
{items.length > 0 && items[0].name.first}
{items.map(item => {
console.log(items);
const {
id,
fileds: { name, votes },
} =item;
return (
<li ley={id}>
<div className="key">
{name.toUpperCase().substring(0,2)}
</div>
<div>
<h4>{name}</h4>
<p>{votes} votes</p>
</div>
<button onClick={() => console.log("clicked")}>
<FaVoteYea />
</button>
</li>
)
})}
</ul>)}
</div>
</Wrapper>
)
}
我认为问题的部分原因在于,在设置为对象数组初始化时,没有给定值(因为我想初始化它)。
const [items, setItems] = React.useState([]);
最后导致问题的部分如下:
{items.length > 0 && items[0].name.first}
{items.map(item => {
console.log(items);
const {
id,
fileds: { name, votes },
} =item;
到目前为止,我学习了 this post 和 this other post。特别是最后一个似乎很有用,但我仍然不精通 Angular
并且还没有完全理解 Typescript
,尽管我正在努力。
然后我也研究了 this 帖子,但仍然找不到我未定义变量的答案。
感谢您对潜在解决方案的指导。
答案 0 :(得分:2)
在 ES6 中,解构让我们简化代码
如你所见
const {
id,
fileds: { name, votes },
} =item
相当于
item.id // some id
item.fileds.name // some name i
item.fields.votes // some votes
在您的情况下,您破坏了对象项目,但文件始终采用经典形式
你的代码应该是
<h4>{fileds.name}</h4>
<p>{fileds.votes} votes</p>