setState가 정의되지 않음
나는 계속 사용하라고 하는 답을 보고 있지만, 두 가지 해결책 모두 효과가 없었다.
import React, { Component } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';
export default class MyWeatherApp extends Component {
constructor(props) {
super(props);
this.state = {};
}
getInitialState() {
return {
zip: '',
forecast: null,
};
}
_handleTextChange(event) {
var zip = event.nativeEvent.text;
this.setState({zip: zip});
}
해결책:
_handleTextChange = (event) => {
var zip = event.nativeEvent.text;
this.setState({zip: zip});
alert('click');
}
당신이 할 때extend
React.Component
ES2015 클래스 구문을 사용하여 작업 핸들러를 클래스의 컨텍스트에 바인딩하십시오.
다음을 시도해 보십시오.onChange={e => _handleTextChange(e)}
일반적으로 화살표 기능을 사용하지 않는 것이 좋다.bind
내부의 방법들render
그 기능들의 새로운 복사본을 생성하기 때문에.render
하십시오. 함수 선언을 다음으로 이동class constructor
.
나는 개인적으로 화살표 기능을 클래스 속성으로 사용하는 것을 선호한다.
class MyClass extends React.Component {
handleClick = () => {
// your logic
};
render() {
return (
<button onClick={this.handleClick}>Click me</button>
);
}
}
ES2015 규격의 부분은 아니지만 babel stage-0 사전 설정은 이 구문을 지원한다.
이 문서의 대응에서 컨텍스트 바인딩에 대한 자세한 내용은
내가 이것을 자세히 쓸게.연구하는데 많은 시간을 허비해야 했기 때문에 아무도 이 일을 반복하지 않았으면 좋겠어...
화살표 기능을 사용하지 않으면 바인딩해야 함this
9호선처럼
class MyClass extends React.Component {
handleButtonClick(){
console.log("Hello from here");
};
render() {
return (
<button onClick={this.handleButtonClick.bind(this)}>Click me</button>
);
}
}
또 다른 방법은 ES6 Arrow 기능을 사용하는 것이다.이 경우에는 '이것'을 속박할 필요가 없다.'바벨 스테이지-1 사전 설정'을 설치하면 이를 뒷받침한다.
프로젝트에서 아래 명령을 실행하십시오.
npm i babel-preset-stage-1 --save
너의 .babelrc는 이렇게 보일 것이다.특히 사전 설정의 '1단계'.
{
"presets": ["es2015", "react", "stage-1"],
"env": {
"development": {
"plugins": ["react-hot-loader/babel"]
}
}
}
네 부품은 이렇게 될 거야, 내가 말했듯이.
class MyClass extends React.Component {
handleButtonClick = () => {
console.log("Hello from here");
};
render() {
return (
<button onClick={this.handleButtonClick}>Click me</button>
);
}
}
문제는 다음과 같았다.나는 그 오류가 있었다: 이것은.setState가 함수가 아님
구성 요소 생성자의 상태에 내 기능을 바인딩하고 있었으므로 다음과 같이 하십시오.
this.getRequestData = this.getRequestData.bind(this);
제 기능은 다음과 같았었죠.
getRequestData(){
axios.post('http://example.com/getInfo', jsonData)
.then(function (res) {
console.log(res);
})
.catch(function (error) {
console.log(error);
});
this.setState({ stateVaribale });
})
}
해결책은 사용하는 것이다.arrow functions
사용하지 않고keyword
공리 요청에서 함수, 구성 요소 상태 대신 공리 요청에서 함수를 참조하기 위해 반응하는 것이 혼동될 수 있음.
getRequestData(){
axios.post('http://example.com/getInfo', jsonData)
.then(res => {
console.log(res);
})
.catch(error => {
console.log(error);
});
this.setState({ stateVaribale });
})}
또한 당신은 이것을 안에 묶을 수 있다.constructor
이것처럼.
class MyClass extends React.Component {
constructor(props){
super(props);
this.handleButtonClick = this.handleButtonClick.bind(this);
}
handleButtonClick(){
console.log("Hello from here");
}
render() {
return (
<button onClick={this.handleButtonClick}>Click me</button>
);
}
}
원초적인 반응에서, 우리는 공리를 예로 들 때 이 오류를 얻었다.
componentDidMount(){
axios.get('https://the request url')
.then( function(response) {
this.setState({products:response.data.products});
})
.catch(function(error) {
console.log(error);
})
}
우리가 이렇게 노력한다면:
정의되지 않은 것은 사물이 아니다.setState'))
어떻게 하면 이것을 고칠 수 있을까, 이런 화살표 기능을 이용해서 고칠 수 있다.
componentDidMount(){
axios.get('https://the request url')
.then( (response)=> {
this.setState({products:response.data.products});
})
.catch((error)=> {
console.log(error);
})
}
이것이 문제를 해결해 줄 것이고, 이것이 도움이 되기를 바란다.
당신이 당신의 행동을 바인딩할 필요가 없다면 당신은 당신의 브라우저에서 정의되지 않은 오류를 볼 수 있다 당신의 행동을 바인딩하는 세 가지 방법이 있다.
- 핸들러를 렌더 메서드에 bind this.chngHandler.bind(이것)
예를 들어
export class EventBind extends Component{
constructor(){
super()
this.state = {
msg:'hello'
}
}
chngHandler(){
this.setState({
msg:'Good bye'
})
}
render(){
return(
<div>
{this.state}
<button onClick={this.chngHandler.bind(this)}>click</button>
</div>
)
} }
- 렌더링 시 화살표 함수 접근법
()=>this.EventHandler()
예를 들어-
export class EventBind extends Component{
constructor(){
super()
this.state = {
msg:'hello'
}
}
chngHandler(){
this.setState({
msg:'Good bye'
})
}
render(){
return(
<div>
{this.state}
<button onClick={()=>this.chngHandler()}>click</button>
</div>
)
}}`
3.시뮬레이터에서 이벤트 핸들러 바인딩this.EventHandler = this.EventHandler.bind(this)
예를 들어-:
export class EventBind extends Component{
constructor(){
super()
this.state = {
msg:'hello'
}
this.chngHandler = this.chngHandler.bind(this)
}
chngHandler(){
this.setState({
msg:'Good bye'
})
}
render(){
return(
<div>
{this.state}
<button onClick={this.chngHandler}>click me </button>
</div>
)
}}
왜냐하면 바인딩은 생성자에서 한 번 발생하기 때문에 렌더 방법에서 바인딩하는 것보다 이것이 더 낫다.
세 번째 접근법도 다음과 같이 할 수 있다.
export class EventBind extends Component{
constructor(){
super()
this.state = {
msg:'hello'
}
this.chngHandler = this.chngHandler.bind(this)
}
// chngHandler(){
// this.setState({
// msg:'Good bye'
// })
// }
chngHandler = ()=>{
this.setState({
msg:'Good Bye'
})
}
render(){
return(
<div>
{this.state}
<button onClick={this.chngHandler}>click me </button>
</div>
)
}}
다른 기능을 호출하는 메소드 내에서 지방 화살표 기능을 사용할 때도 반응한다.예를 들면.then((response) => { this.setState({....}) }
이것을 axios request와 같은 api call 안에서 사용할 때마다 당신의 'this' 컨텍스트가 정의되지 않은 경우가 있다.여기서 몇 가지 세부사항을 설명하자면 다음과 같다.
`
import react from 'React'
class Test extends from React.Component {
constructor() {
super();
this.state = {
data: '',
error: ''
}
}
componentDidMount() {
url = 'http://abc.go.com';
axios.get(url).then(function(resposne) { // Everything fine till now
this.setState({ data: response }); //Oops this context is undefined
}
).catch(function(err) {
this.setState({ error: err }); // again this context remains to be undefined
});
}
render() {
return ( <div>this.state.data</div> )
}
}`
위의 코드를 실행할 때 setState of undefined가 호출되고 있는 것과 유사한 유형의 오류가 분명히 나타날 것이다.
어떻게 해결할 수 있어?이 특정한 유형의 문제를 해결하기 위해 따를 수 있는 두 가지 방법이 있다.
첫째, api를 호출할 함수 내에서 변수를 정의하고 '이것'의 값을 할당할 수 있으며, 이 변수에서 상태 개체를 참조할 수 있다.
import react from 'React'
class Test extends React.Component
{
constructor() {
super();
this.state = {
data: '',
error: ''
};
componentDidMount() {
let url = 'http://abc.go.com';
currentContext = this; // variable to be assigned this context
axios.get(url).then(function(resposne) { // Everything fine till now
currentContext.setState({ data: response }); //Oops this context is undefined
}
).catch(function(err) {
currentContext.setState({ error: err }); // again this context remains to be undefined
});
}
render() {
return ( <div>this.state.data</div> )
}
}
두 번째 방법은 아래와 같이 공리에서 화살표 함수를 정의하는 것이다.
axios.get(url).then((response) => {
this.setState({ data: response }) //will always be bound to the this context
})
참조URL: https://stackoverflow.com/questions/39210971/this-setstate-is-undefined
'programing' 카테고리의 다른 글
Vuex - 대용량 데이터 집합 처리 방법(항목 개별 부하) (0) | 2022.04.04 |
---|---|
가상 환경 제거/삭제 방법 (0) | 2022.04.04 |
npm 패키지의 덮어쓰기 유형 정의 (0) | 2022.04.03 |
Vue 프로젝트의 보기와 구성 요소 폴더 간의 차이점은? (0) | 2022.04.03 |
페이지 새로 고침 시 NextJS에서 Redex 상태를 올바르게 수산화하는 방법 (0) | 2022.04.03 |