반응 - 수집되지 않은 유형 오류: 정의되지 않은 속성 'setState'를 읽을 수 없습니다.
다음과 같은 오류가 발생하였습니다.
Uncaughed TypeError: 정의되지 않은 속성 'setState'를 읽을 수 없습니다.
컨스트럭터에서 델타 바인드 후에도 마찬가지입니다.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta.bind(this);
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
이 이유는this.delta
얽매이지 않다this
.
바인드 세트를 작성하려면this.delta = this.delta.bind(this)
컨스트럭터:
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta = this.delta.bind(this);
}
현재 바인드를 호출하고 있습니다.그러나 bind는 바인딩된 함수를 반환합니다.함수를 바운드 값으로 설정해야 합니다.
ES7+(ES2016)에서는 experimental function bind 구문 연산자를 사용할 수 있습니다.::
묶다.그것은 통사적인 설탕이며 데이빈 트라이언의 대답과 같은 역할을 할 것이다.
그런 다음 다시 쓸 수 있습니다.this.delta = this.delta.bind(this);
로
ES6+(ES2015)의 경우 ES6+ 화살표 기능도 사용할 수 있습니다(=>
)를 사용할 수 있도록 합니다.this
.
delta = () => {
this.setState({
count : this.state.count + 1
});
}
왜? Mozilla 문서에서:
화살표가 기능할 때까지 모든 새로운 함수는 이 값을 정의합니다[...].이것은 객체 지향적인 프로그래밍 스타일로 인해 성가신 것으로 판명되었습니다.
화살표 함수는 포위 컨텍스트의 이 값을 캡처합니다 [...]
ES5 클래스와 ES6 클래스 사이에는 컨텍스트의 차이가 있습니다.따라서 구현 간에 약간의 차이도 있을 것입니다.
ES5 버전은 다음과 같습니다.
var Counter = React.createClass({
getInitialState: function() { return { count : 1 }; },
delta: function() {
this.setState({
count : this.state.count++
});
},
render: function() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
});
ES6 버전은 다음과 같습니다.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count : 1 };
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta.bind(this)}>+</button>
</div>
);
}
}
클래스 구현 구문의 차이 외에 이벤트핸들러 바인딩에도 차이가 있으므로 주의해 주십시오.
ES5 버전에서는
<button onClick={this.delta}>+</button>
ES6 버전에서는 다음과 같습니다.
<button onClick={this.delta.bind(this)}>+</button>
아무것도 바인딩할 필요가 없습니다.그냥 다음과 같은 Arrow 기능을 다음과 같이 할 수 있습니다.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 1
};
}
//ARROW FUNCTION
delta = () => {
this.setState({
count: this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
Respect에서 ES6 코드를 사용할 때는 항상 화살표 기능을 사용합니다. 이 컨텍스트는 자동으로 이 코드와 바인딩되기 때문입니다.
사용방법:
(videos) => {
this.setState({ videos: videos });
console.log(this.state.videos);
};
다음 대신:
function(videos) {
this.setState({ videos: videos });
console.log(this.state.videos);
};
메서드를 'this'(기본 개체)로 바인딩해야 합니다.따라서 어떤 기능이든 간에 컨스트럭터에 바인드하기만 하면 됩니다.
constructor(props) {
super(props);
this.state = { checked:false };
this.handleChecked = this.handleChecked.bind(this);
}
handleChecked(){
this.setState({
checked: !(this.state.checked)
})
}
render(){
var msg;
if(this.state.checked){
msg = 'checked'
}
else{
msg = 'not checked'
}
return (
<div>
<input type='checkbox' defaultChecked = {this.state.checked} onChange = {this.handleChecked} />
<h3>This is {msg}</h3>
</div>
);
다음 항목도 사용할 수 있습니다.
<button onClick={()=>this.delta()}>+</button>
또는 다음 중 하나를 선택합니다.
<button onClick={event=>this.delta(event)}>+</button>
만약 당신이 몇 개의 파라메스를 통과하고 있다면..
에서 ES5 구문을 사용하고 있는 경우는, 올바르게 바인드 할 필요가 있습니다.
this.delta = this.delta.bind(this)
ES6 이상을 사용하고 있다면 화살표 기능을 사용할 수 있으므로 bind()를 사용할 필요가 없습니다.
delta = () => {
// do something
}
이를 컨스트럭터에 바인드하고 컨스트럭터에 변경을 가하면 서버를 재시작해야 합니다.그렇지 않으면 동일한 오류로 끝납니다.
아래에 언급하는 바와 같이 이 키워드로 새로운 이벤트를 묶어야 합니다.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta = this.delta.bind(this);
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
이 오류는 다양한 방법으로 해결할 수 있습니다.
ES5 구문을 사용하는 경우 React js Documentation에 따라 바인드 방법을 사용해야 합니다.
위의 예에서는 다음과 같습니다.
this.delta = this.delta.bind(this)
ES6 구문을 사용하는 경우 바인드 방식을 사용할 필요가 없습니다.다음과 같은 방법으로 실행할 수 있습니다.
delta=()=>{ this.setState({ count : this.state.count++ }); }
이 문제에는 다음 두 가지 해결책이 있습니다.
첫 번째 솔루션은 구성 요소에 컨스트럭터를 추가하고 다음과 같이 함수를 바인딩하는 것입니다.
constructor(props) {
super(props);
...
this.delta = this.delta.bind(this);
}
다음 작업을 수행합니다.
this.delta = this.delta.bind(this);
이것 대신:
this.delta.bind(this);
두 번째 해결책은 화살표 기능을 사용하는 것입니다.
delta = () => {
this.setState({
count : this.state.count++
});
}
실제로 화살표 기능은 자체 바인딩되지 않습니다.this
. 으로 기능합니다 화살표입니다.bind
그들의 문맥은 그렇게this
는, 실제로는, 발신기지 콘텍스트를 참조하고 있습니다.
바인드 함수에 대한 자세한 내용은 다음을 참조하십시오.
화살표 기능에 대한 자세한 내용은 다음을 참조하십시오.
ES6 — Lexical Javascript ES6 — 화살표 기능this
화살표 기능을 사용하면 이 키워드의 구속을 피할 수 있습니다.다음과 같은 경우:
delta = () => {
this.setState({
count : this.state.count++
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component{
constructor(props){
super(props);
this.state = {
counter : 0,
isToggle: false
}
this.onEventHandler = this.onEventHandler.bind(this);
}
increment = ()=>{
this.setState({counter:this.state.counter + 1});
}
decrement= ()=>{
if(this.state.counter > 0 ){
this.setState({counter:this.state.counter - 1});
}else{
this.setState({counter:0});
}
}
// Either do it as onEventHandler = () => {} with binding with this // object.
onEventHandler(){
this.setState({isToggle:!this.state.isToggle})
alert('Hello');
}
render(){
return(
<div>
<button onClick={this.increment}> Increment </button>
<button onClick={this.decrement}> Decrement </button>
{this.state.counter}
<button onClick={this.onEventHandler}> {this.state.isToggle ? 'Hi':'Ajay'} </button>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('root'),
);
</script>
</body>
</html>
bind 스테이트먼트를 기존의 bind 스테이트먼트에서 => this.timeout = this.timeout.timeout(this)로 변경합니다.
추가 중
클릭={this.delta.bind(this)}
이 에러는 ES6 클래스의 함수를 호출하려고 할 때 발생합니다.따라서 메서드를 바인드할 필요가 있습니다.
이 질문에는 이미 해답이 있었습니다만, 확실히 하기 위해서 제 질문을 공유하고 싶습니다.이 질문에 도움이 되었으면 합니다.
/*
* The root cause is method doesn't in the App's context
* so that it can't access other attributes of "this".
* Below are few ways to define App's method property
*/
class App extends React.Component {
constructor() {
this.sayHi = 'hello';
// create method inside constructor, context = this
this.method = ()=> { console.log(this.sayHi) };
// bind method1 in constructor into context 'this'
this.method1 = this.method.bind(this)
}
// method1 was defined here
method1() {
console.log(this.sayHi);
}
// create method property by arrow function. I recommend this.
method2 = () => {
console.log(this.sayHi);
}
render() {
//....
}
}
- 특정 속성을 생성하는지 여부를 상태 확인
this.state = {
name: "",
email: ""
}
this.setState(() => ({
comments: comments //comments not available in state
}))
2. 함수 내에서 setState를 실행하는 경우(즉, handleChange), 함수가 이 함수에 바인드되는지 또는 함수가 화살표 함수가 되어야 하는지 여부를 확인합니다.
## 이것을 아래 함수에 바인드하기 위한 3가지 방법##
//3 ways for binding this to the below function
handleNameChange(e) {
this.setState(() => ({ name }))
}
// 1.Bind while callling function
onChange={this.handleNameChange.bind(this)}
//2.make it as arrow function
handleNameChange((e)=> {
this.setState(() => ({ name }))
})
//3.Bind in constuctor
constructor(props) {
super(props)
this.state = {
name: "",
email: ""
}
this.handleNameChange = this.handleNameChange.bind(this)
}
inside axios 를 사용하고 있는 경우는, 다음의 화살표(=>) 를 사용합니다.
axios.gethttp://abc.com').then(응답) => {} ;
Axios 또는 fetch 또는 get을 사용할 때 동일한 sulation을 찾는 사용자가 있을 경우 setState를 사용하면 이 오류가 반환됩니다.
이렇게 컴포넌트를 외부에서 정의해야 합니다.
componentDidMount(){
let currentComponent = this;
axios.post(url, Qs.stringify(data))
.then(function (response) {
let data = response.data;
currentComponent.setState({
notifications : data.notifications
})
})
}
언급URL : https://stackoverflow.com/questions/32317154/react-uncaught-typeerror-cannot-read-property-setstate-of-undefined
'programing' 카테고리의 다른 글
Java에서 정수를 부동으로 변환하려면 어떻게 해야 합니까? (0) | 2022.09.19 |
---|---|
JavaScript: .forEach()와 .map()의 차이점 (0) | 2022.09.19 |
필드의 "길이"에 대한 MySQL SELECT 문이 1보다 큽니다. (0) | 2022.09.19 |
PHP에서 정수가 숫자의 범위 내에 있는지 확인하는 방법은 무엇입니까? (0) | 2022.09.19 |
Python에서 스레딩을 사용하려면 어떻게 해야 하나요? (0) | 2022.09.19 |