React에서 증분 연산자를 사용하는 방법
왜 내가 하고 있을 때this.setState({count:this.state.count*2})
동작하고 있습니다만, 동작하고 있는 경우는, 다음과 같습니다.this.setState({count:this.state.count++})
안 돼요?
왜, 어떻게 고치나요?
풀코드:
var Hello = React.createClass({
getInitialState:function(){
return {count:parseInt(this.props.count)}
},
a:function(){
this.setState({count:this.state.count++})
console.log(this.state)
},
render: function() {
console.log(this.state)
return <div onClick={this.a}>Click to increment the counter<b> {this.state.count} </b></div>;
}
});
ReactDOM.render(
<Hello count="1" />,
document.getElementById('container')
);
하지만 이 코드는 작동합니다.
a:function(){
this.setState({count:this.state.count*2})
console.log(this.state)
},
JSFiddle:https://jsfiddle.net/69z2wepo/55100/
setState
는 비동기 함수입니다.리액션으로 인해 많은 양의setState
함께 합니다.그래서 그 가치는this.state.count
는요구시점의값입니다.
setState 실행 시 평가되는 함수를 호출하기 위한 더 나은 솔루션.
this.setState((prevState, props) => ({
counter: prevState.counter + 1
}));
https://facebook.github.io/react/docs/state-and-lifecycle.html 에서
함으로써this.state.count++
주(州)를 변화시키는 것은this.state.count += 1
. 상태를 변환하지 마십시오(https://facebook.github.io/react/docs/component-api.html) 참조).대신 이 작업을 수행하는 것이 좋습니다.
this.setState({ count: this.state.count + 1 })
그setState
함수가 먼저 반환되다this.state.count
는 post-fix 연산자(+)를 사용하고 있기 때문에 증가합니다.또한.setState
는 비동기이며 상태가 갱신되었을 때 트리거되는두 번째 인수로 콜백을 받아들이기 때문에,console.log
CB 안에요.
상태를 변환하려고 합니다(this.state에 액세스합니다).++가 바로 그것입니다.이 상태 값을 증가시켜 새로운 상태에 할당하려고 합니다. :) setState를 호출하여 상태를 변환합니다.해라
this.setState({count: this.state.count+1})
또는
this.setState({(state)=>({count: state.count + 1})}
// 함수의 범위 내에 있는 새로운 상태 변수, 심지어 안전하게 ++를 가지고 놀 수 있습니다. 하지만 이 상태에서는 ++를 호출하지 마십시오.일반적으로 ++를 사용하지 마십시오. 나쁜 관행입니다.
간단한 할당의 경우
a+=1 || a-=1 || a*=1 || a%=1
더 낫거나, 심지어 그것들을 명시적으로 쓰기도 합니다.
a = a + 1
바인드(이) 함수를 사용하여 바인드할 수 있습니다(예:-).
<div onClick={this.increase.bind(this)}>
또는 다음과 같이 바인드되는 화살표 함수를 사용할 수 있습니다.
<div onClick={()=> this.increase()} >
또 다른 이유는 "something++"가 값을 뮤트하지만 OLD VALUE를 반환하기 때문입니다. "++something"도 같은 방식으로 뮤트 +1을 반환하지만 NEW VALUE를 반환합니다.
a = 3
console.log(a++) // Will log out the OLD VALUE 3, but in memory `a` will be mutated into 4
console.log(a++) // Will log out OLD VALUE 4, but in memory `a` will be mutated into 5
console.log(++a) // Will log out 6, since 5+1=6 is the new value
그러나 전체적으로 React에서 상태를 변환하지 마십시오.
이것이 너에게 도움이 되길 바란다.
import { render } from '@testing-library/react';
import React, { Component } from 'react';
class Counter extends Component{
state = {
count: 0,
};
handleIncrement = () => {
this.setState({ count: this.state.count + 1 })
};
handleDecrement = () => {
this.setState({ count: this.state.count - 1 })
};
render(){
return(
<div>
<button onClick={this.handleIncrement} className="btn btn-secondary btn-sm m-4 ">Increment</button>
<span className = "badge bg-primary m-5">{this.state.count}</span>
<button onClick={this.handleDecrement} className="btn btn-secondary btn-sm ">Decrement</button>
</div>
)
}
};
export default Counter;
이벤트 발생 시 카운터의 증가, 감소 및 리셋에는 위의 스니펫을 사용할 수 있습니다.
import { useState } from "react";
const Count = () => {
const [num, setNum] = useState(0);
const CounterI = () => {
setNum (num+1);
}
const CounterD = () => {
setNum (num-1);
}
const ResetCounter = () =>{
setNum (0);
}
return(
<div>
<p>Count Value: {num}</p>
<button onClick={CounterI}>Counter Increment</button>
<button onClick={CounterD}>Counter Decrement</button>
<button onClick ={ResetCounter} >Reset</button>
</div>
);
}
export default Count;
해결책을 찾았어요할 때this.setState({count:++this.state.count})
되고 있어요.
그 이유는 내가 하고 있을 때this.setState({count:this.state.count++})
새것state.count
에 송신되지 않는 값setState
리액트
언급URL : https://stackoverflow.com/questions/39316376/how-to-use-the-increment-operator-in-react
'programing' 카테고리의 다른 글
JPA 과도 주석 및 JSON (0) | 2023.02.26 |
---|---|
워드프레스, pre_get_posts에 여러 meta_key가 있습니다. (0) | 2023.02.26 |
React-Router - Uncaught TypeError: 정의되지 않은 속성 'getCurrentLocation'을 읽을 수 없습니다. (0) | 2023.02.26 |
PHP로 WordPress 플러그인에서 텍스트 파일로 쓰기 (0) | 2023.02.26 |
키보드 회피 Scroll View를 사용한 표시 회피 (0) | 2023.02.26 |