미정의 In React 확인
환원기에서 반응 상태로 데이터를 전달하는 시나리오가 있습니다.
데이터:
{
"id": 1,
"title": "Test",
"content": {
"body": "sdfsdf"
"image": "http://example.com"
}
}
componentWillReceiveProps를 사용하면 제목 취득에 매우 적합합니다.
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps.blog.title,
})
}
그러나 중첩된 필드를 검색하는 데 문제가 있습니다.이렇게 하면:
componentWillReceiveProps(nextProps) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
다음의 에러가 표시됩니다.
디버거를 클릭하여 콘텐츠를 로드하면 정의되지 않은 본문의 오류가 사라집니다.이 문제에 대처할 방법이 없을까요?
다음과 같이 정의되지 않았는지 확인하려고 했습니다.
if (typeof nextProps.blog.content["body"] != 'undefined'){
하지만 이것도 효과가 없고 블로그가 정의되어 있지 않기 때문이라고 생각합니다.
당신이 할 수 있는 것은 소품이 처음에 정의되어 있는지 아닌지를 체크하는 것입니다.nextProps.blog.content
정의되지 않았거나 정의되지 않았거나 몸이 그 안에 내포되어 있기 때문입니다.
componentWillReceiveProps(nextProps) {
if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
}
유형을 사용하여 정의되지 않았는지 확인할 필요는 없으며, 엄밀한 연산자만 사용할 수 있습니다.!==
유형 및 가치별로 값을 비교합니다.
정의되어 있지 않은지 확인하려면typeof
연산자 같은
typeof nextProps.blog.content != "undefined"
나도 같은 문제에 직면했었어..그리고 나는 그것을 이용하여 해결책을 얻었다.typeof()
if (typeof(value) !== 'undefined' && value != null) {
console.log('Not Undefined and Not Null')
} else {
console.log('Undefined or Null')
}
를 사용해야 합니다.typeof()
식별하다undefined
혹시라도 확인하실 필요가 있는 경우nextProps.blog
아니다undefined
싱글로 할 수 있습니다.if
다음과 같은 스테이트먼트를 나타냅니다.
if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
//
}
그리고...undefined
,empty
또는null
값은 예상되지 않습니다. 보다 간결하게 할 수 있습니다.
if (nextProps.blog && nextProps.blog.content) {
//
}
다음과 같이 물음표를 추가해 볼 수 있습니다.이건 나한테 효과가 있었어.
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps?.blog?.title,
body: nextProps?.blog?.content
})
}
아래 코드를 사용하여 정의되지 않은 개체를 확인할 수 있습니다.
ReactObject === '오류'
언급URL : https://stackoverflow.com/questions/40735406/checking-for-undefined-in-react
'it-source' 카테고리의 다른 글
소계 카트 변수 php WooCommerce (0) | 2023.03.27 |
---|---|
컴포넌트에 대한 리액트라우터 패스 파라미터 (0) | 2023.03.22 |
PLIST를 JSON으로 변환하기 위한 명령줄 도구? (0) | 2023.03.22 |
bigint: 12000000000002539의 JSON 전송은 12000000000002540으로 변환됩니까? (0) | 2023.03.22 |
WordPress를 사용하여 URL 개서를 위해 Windows Azure를 설정하는 방법 (0) | 2023.03.22 |