我想建立一個網絡應用程序,計算每天應該爲未來旅行節省多少錢(我知道它可以很容易地通過一個簡單的計算器來完成,但這是爲學習的緣故)。反應:狀態不是實時渲染
我的問題是,當我在兩個輸入中輸入成本和時間時,日常儲蓄計算不會實時呈現在DOM上。
這裏是會發生什麼:
- I型在第一輸入(成本要素內)成本和留在第二輸入的天數(的timeleft組件內)
- 的DOM使兩者的成本而留在我鍵入時(在
{this.state.totalCost}
和{this.state.timeLeft}
- 的計算結果
{this.state.dailyCost}
呈現了「一個變」延遲(即成本= 100 = 10 我需要輸入一些東西剩下的天實時天否則像添加一個0的成本爲10在DOM中渲染爲正確的結果的計算。)
謝謝你的幫助!我希望我以一種可以理解的方式解釋。
我的代碼:
class App extends Component {
constructor() {
super();
this.state = {
totalCost: 0,
timeLeft: 0,
dailyCost: 0,
}
}
updateDailySavings() {
if (this.state.timeLeft !== 0) {
this.setState({dailyCost: (this.state.totalCost/this.state.timeLeft).toFixed(2)});
} else {
this.setState({dailyCost: 0});
}
}
changeCost(newCost) {
this.setState({totalCost: Math.round(newCost)});
this.updateDailySavings()
}
changeTimeLeft(newTimeLeft) {
this.setState({timeLeft: Math.round(newTimeLeft)});
this.updateDailySavings()
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<Cost changeCost={this.changeCost.bind(this)}/>
<TimeLeft changeTimeLeft={this.changeTimeLeft.bind(this)}/> <br/>
<div>You have to save £{this.state.totalCost} in the next {this.state.timeLeft} days.<br/>
You have to save £{this.state.dailyCost} per day.
</div>
</div>
);
}
}
'setState'是異步的。如果您需要立即使用狀態值,則應該使用回調。 'this.setState({some:'value'},()=> {/ * .. doSometing .. * /})' – bennygenel