React
사용자가 다른 선택 항목 중에서 찬성 투표를할지 여부를 결정할 수 있는 작은 설문 조사 구성 요소를 만들고 있습니다. 투표는 Airtable을 통해 "Survey"라는 테이블에 등록됩니다.
내가 가진 문제는 터미널에서 다음과 같은 오류가 발생한다는 것입니다 .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>
)
}
문제의 일부는 객체 배열의 초기화로 pourposly 설정된 라인 블로우에 값이 주어지지 않았기 때문이라고 생각합니다 (초기화하고 싶었 기 때문에).
const [items, setItems] = React.useState([]);
결국 문제를 일으키는 부분은 다음과 같습니다.
{items.length > 0 && items[0].name.first}
{items.map(item => {
console.log(items);
const {
id,
fileds: { name, votes },
} =item;
지금 까지이 포스트 와 다른 포스트를 공부했습니다 . 부분적으로는 마지막 것이 유용 해 보이지만 아직 작업 중이지만 아직 능숙 Angular
하지 않고 완전히 이해 Typescript
하지 못했습니다.
그런 다음 이 게시물 을 연구 했지만 정의되지 않은 변수에 대한 답을 찾을 수 없었습니다.
잠재적 인 솔루션을 안내해 주셔서 감사합니다.
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>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다