반응 - TypeError: 정의되지 않은 속성 'props'를 읽을 수 없습니다.
목록에서 항목을 삭제할 수 있도록 클릭 이벤트를 생성하려고 하는데 이 이벤트를 클릭하면 "TypeError: Unread property 'props of defined"라는 메시지가 나타납니다.
가능한 한 ES6를 고집하려고 하고 있고, 어딘가에서 '이것'을 구속하는 것은 틀림없다고 생각합니다만, 많은 곳을 시도했지만 성공하지 못했습니다.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<StreetFighter />
</div>
);
}
}
class StreetFighter extends Component {
constructor(props) {
super(props);
this.state = {
characters: [
'Chun-Li',
'Guile',
'Ryu',
'Ken',
'E.Honda',
'Dhalsim',
],
};
}
render() {
let characters = this.state.characters;
characters = characters.map((char, index) => {
return (
<Character char={char} key={index} onDelete={this.onDelete} />
);
});
return (
<div>
<p>Street Fighter Characters</p>
<ul>{characters}</ul>
</div>
);
}
onDelete(chosenCharacter) {
let updatedCharactersList = this.state.characters.filter(
(char, index) => {
return chosenCharacter !== char;
}
);
this.setState({
characters: updatedCharactersList,
});
}
}
class Character extends Component {
render() {
return (
<li>
<div className="character">
<span className="character-name">{this.props.char}</span>
<span
className="character-delete"
onClick={this.handleDelete}
> x </span>
</div>
</li>
)
};
handleDelete() {
this.props.onDelete(this.props.char);
}
}
export default App;
TLDR: 코드의 특정 문제는 이 답변의 끝에 있는 단락에 기재되어 있습니다.
이것은 JavaScript의 전형적인 문제입니다.아직 읽어보시지 않았다면 조금 읽어보시는 것이 좋습니다.
간단히 말하면(자신을 위해서뿐만 아니라 다른 사람이 이것을 읽고 있는 경우), JavaScript 함수 정의(화살표 함수로 작성되지 않은 경우)는 다음을 재정의합니다.this
즉, 무엇을 가리키고 있는가 하는 것입니다.정의하면 다음과 같이 됩니다.
handleDelete() {
this.props.onDelete(this.props.char);
}
그 기능은this
는 정의된 클래스의 오브젝트인스턴스를 가리키고 있지 않습니다.C++/C#/Java 출신이라면 이는 다소 직관에 어긋납니다.중요한 것은 말이다this
클래스가 JavaScript에 들어가 클래스가 정의된 프로토타입(여기를 참조)을 포함한 함수에 대한 구문설탕 이상을 주목하기 전에 종료됩니다.즉, 기본적으로는 이 기능을 함수에 바인딩하지 않습니다.
여기에는 몇 가지 일반적인 방법이 있습니다.
바인드this
(컨스트럭터의) 모든 함수에 대해
class Character extends Component {
constructor(props) {
super(props)
this.handleDelete = this.handleDelete.bind(this)
}
render() {
// ...
};
handleDelete() {
this.props.onDelete(this.props.char);
}
}
메모: 이 대신 기능을 사용할 때마다 바인딩할 수 있습니다(예:onClick={this.handleDelete.bind(this)}
단, 바인딩을 잊어버린 경우 오류가 발생하기 쉽기 때문에 권장하지 않습니다.this
또, 기능 체인을 하고 있는 경우는, 어딘가 잘못된 점을 지적하는 경우가 있습니다.말할 것도 없이bind
함수로, 리액트에서는 모든 렌더링에 대해 함수 호출이 이루어집니다.하지만, 만약 여러분이 변화해야 하는 상황이 생긴다면, 명심하는 것은 좋은 일입니다.
화살표 기능 사용
class Character extends Component {
render() {
// ...
};
handleDelete = () => {
this.props.onDelete(this.props.char);
}
}
위에서 설명한 바와 같이, 다른 답변에서 화살표 함수는 다음을 재정의하지 않습니다.this
포인터여기서는 화살표 함수를 이 클래스의 오브젝트인스턴스 속성에 할당하고 있습니다.즉, 기능(재정의되지 않은 화살표 기능)this
은(는)를 취합니다.this
그러나 화살표 함수는 익명 함수이므로 이름 속성에 할당하여 이름을 지정합니다.
기타 모든 솔루션은 위의 두 가지 솔루션 중 일부 버전입니다.
솔루션에 대해서
다.onDelete
★★★★★★★★★★★★★★★★★」handleDelete
에 this
disclossible을 클릭합니다.
또한 @Alyson Maia가 위에서 말했듯이, 당신의Character
컴포넌트는 기능 컴포넌트로 작성할 수 있습니다.
const Character = (props) => {
render() {
return (
<li>
<div className="character">
<span className="character-name">{this.props.char}</span>
<span
className="character-delete"
onClick={props.onDelete(props.char)}
> x </span>
</div>
</li>
)
};
}
JS OOP 시스템 때문에 클래스 메서드의 콘텍스트를 이렇게 소품에 전달할 때 다시 씁니다.이를 실현하기 위해서는 몇 가지 방법이 있습니다.
1) Bind는 항상 새로운 기능을 반환하고, 소품 업데이트가 없어도 컴포넌트가 다시 렌더링되기 때문에 그다지 좋지 않습니다.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<StreetFighter />
</div>
);
}
}
class StreetFighter extends Component {
constructor(props) {
super(props);
this.state = {
characters: [
'Chun-Li',
'Guile',
'Ryu',
'Ken',
'E.Honda',
'Dhalsim',
],
};
}
render() {
let characters = this.state.characters;
characters = characters.map((char, index) => {
return (
<Character char={char} key={index} onDelete={this.onDelete.bind(this)} />
);
});
return (
<div>
<p>Street Fighter Characters</p>
<ul>{characters}</ul>
</div>
);
}
onDelete(chosenCharacter) {
let updatedCharactersList = this.state.characters.filter(
(char, index) => {
return chosenCharacter !== char;
}
);
this.setState({
characters: updatedCharactersList,
});
}
}
class Character extends Component {
render() {
return (
<li>
<div className="character">
<span className="character-name">{this.props.char}</span>
<span
className="character-delete"
onClick={this.handleDelete.bind(this)}
> x </span>
</div>
</li>
)
};
handleDelete() {
this.props.onDelete(this.props.char);
}
}
export default App;
2) 제 코드에서 화살표 함수를 클래스 속성으로 사용하고 있습니다(가장 일반적인 솔루션 중 하나라고 생각합니다).
class Character extends Component {
render() {
return (
<li>
<div className="character">
<span className="character-name">{this.props.char}</span>
<span
className="character-delete"
onClick={this.handleDelete}
> x </span>
</div>
</li>
)
};
handleDelete = () => {
this.props.onDelete(this.props.char);
}
}
이벤트를 처리하는 함수를 만들 때는 다음과 같이 컨스트럭터를 통해 소품에 추가하는 것을 잊지 마십시오.
constructor (props) {
super(props)
this.yourFunction = this.yourFunction.bind(this)
}
기능을 풀 수 .this
이렇게 해보세요.
이벤트 onClick onClick={this.handleDelete}
기능 정의:
handleDelete = () => {
//here you can access the this.props
}
, 「 」를 사용하고 경우입니다.this
에 inside inside inside handleDelete
클래스를 참조하고 있지 않습니다.할 수 .
상태 비저장 컴포넌트 사용(고객의 경우 최적의 접근법)
는, 「Components」는 「Components」로 할 는 없습니다.Class
나 상수로 할 수
Class Parent extends React.Component {
state = { ... }
onDelete = () => { ... }
render() {
return (
<Child onDelete={this.onDelete} />
)
}
}
function Child(props) {
return (
<button onClick={props.onDelete}>Delete</button>
)
}
화살표 기능 사용
화살표 함수는 스코프를 정의하지 않습니다. 화살표 함수 내에서는 클래스 스코프에 속합니다.
Class Parent extends React.Component {
state = { foo: 'bar' }
wrongMethod() {
console.log(this.state) // undefined
}
rightMethod = () => {
console.log(this.state) // { foo: 'bar' }
}
render() {
this.wrongMethod()
this.rightMethod()
return (
<h1>Hello World!</h1>
)
}
}
바인드 사용
「 」를 사용하는 이 있는 .this
메서드 스코프를 클래스 스코프에 바인드해야 합니다.을 사용하다bindOnRender
모든 렌더링에 대해 호출되고 각 호출에 대해 새로운 함수를 생성해야 하는 성능 문제가 있습니다.
Class Parent extends React.Component {
constructor() {
this.state = { foo: 'bar' }
this.bindOnConstructor.bind(this)
}
bindOnConstructor() {
console.log(this.state) // { foo: 'bar' }
}
bindOnRender = () => {
console.log(this.state) // { foo: 'bar' }
}
render() {
return (
<button onClick={this.bindOnConstructor}>Foo</button>
<button onClick={this.bindOnRender.bind(this)}>Bar</button>
)
}
}
언급URL : https://stackoverflow.com/questions/50862192/react-typeerror-cannot-read-property-props-of-undefined
'code' 카테고리의 다른 글
JSON.stringify 함수 (0) | 2023.03.09 |
---|---|
Swift 4 Codable, 단일 루트 레벨 키로 객체를 디코딩하는 방법 (0) | 2023.03.09 |
PowerShell의 Invoke-WebRequest에서 JSON을 해석하는 방법 (0) | 2023.03.09 |
반응 원어민으로 키보드 숨기기 (0) | 2023.03.09 |
지정된 항목으로 스크롤하는 AngularJS 지시어 (0) | 2023.03.09 |