【发布时间】:2021-03-04 15:51:50
【问题描述】:
我正在React 中构建一个小型调查组件,用户可以在其中决定是否在不同的选项中投票。投票通过Airtable在名为“调查”的表格中登记
我遇到的问题是我在终端中收到一个名为:TypeError: Cannot read property 'name' of undefined`的错误
这似乎与具有 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>
)
}
我认为问题的一部分是由于线吹,在 purposly 设置为对象数组的初始化时,没有给出任何值(因为我想初始化它)。
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 的帖子,但仍然找不到我未定义变量的答案。
感谢您指导潜在的解决方案。
【问题讨论】:
标签: javascript reactjs airtable