2016-06-15 3 views
0

두 입력에서 연산을 수행하려고합니다. 먼저 상태를 업데이트 한 다음 새로 업데이트 된 상태로 두 개의 값을 추가합니다. React.JS 상태 값이 두 개 있습니다.

<input type="number" onChange={this.handleIncomeChange.bind(this)} value={this.state.income} /> 

이 코드

가 작동하지 않습니다 :

handleIncomeChange(e) { 
    this.setState({income: e.target.value}); 
    this.state.resultMonth = +this.state.income - +this.state.expense; 
} 

이 코드가 작동 (결과는 항상 하나 개의 번호 뒤에이다) : I 반응의 개념을 이해하면 확실하지

handleIncomeChange(e) { 
    const income = e.target.value; 
    this.state.resultMonth = +income - +this.state.expense; 
    this.setState({income: e.target.value}); 
} 

. JS 상태. 첫 번째 코드가 작동하지 않는 이유를 확실히 이해하지 못합니다.

답변

4

this.state =을 사용하여 상태를 직접 수정하면 안됩니다 (상태 초기화 중에는 제외). setState API를 사용하여 모든 주 수정을하십시오. 예를 들어

:

handleIncomeChange(e) { 
    const newIncome = e.target.value; 
    this.setState({ 
    income: newIncome, 
    resultMonth: newIncome - this.state.expense 
    }); 
} 

업데이트 : 아래의 의견에 OP에 의해 기술 codepen과 문제에 따라.

재사용 문제를 해결하기 위해 다음과 같이 할 수 있습니다.

handleDataChange(income, expense) { 
    this.setState({ 
    income: income, 
    expense: expense, 
    resultMonth: income - expense 
    }); 
} 

handleIncomeChange(e) { 
    const newIncome = e.target.value; 
    this.handleDataChange(newIncome, this.state.expense); 
} 

handleExpenseChange(e) { 
    const newExpense = e.target.value; 
    this.handleDataChange(this.state.income, newExpense); 
} 
+0

handleIncomeChange '(E) { \t \t newIncome = CONST e.target.value; \t \t this.setState ({ \t \t \t 수입 : newIncome, \t \t \t resultMonth : newIncome - this.state.expense \t \t}); \t \t this.showinfo()} \t \t은 showInfo() { \t \t CONSOLE.LOG (resultMonth); \t} ' 이 함수를 사용하면 여전히 "한 걸음 뒤로 물러나 있습니다". 이 작업을 올바르게 수행하는 방법을 알고 있습니까? –

+1

'this.setState'는 동 기적으로 실행된다는 보장이 없으므로'this.setState'를 호출 한 직후에'this.state'를 로깅하려고하면 업데이트 된 결과를 볼 수 없습니다. 대신에'render()'또는 라이프 사이클 메소드 중 하나 (예 : componentWillUpdate (nextProps, nextState))를 통해 업데이트 된 상태에 액세스해야합니다. 'showInfo'에서 무엇을하려고합니까? 이 질문을 업데이트하면 추천을 할 수 있습니다. 대부분 render()에서 이것을 처리 할 수있다. – ctrlplusb

+0

'showInfo'는 테스트 목적으로 만 사용됩니다. 모든 변경이 업데이트 된 값으로 연산을 수행하는 함수를 실행하는 많은 입력을 통해 양식을 얻고 싶습니다. 비슷한 것 :'calculate {this.state.expense-this.state.income + this.state.tax} ' –

관련 문제