我想有两个输入数字字段value1
和value2
并添加这两个字段的值。然后sum
将保存在this.state.sum
中。我也不想使用“提交”按钮。一些代码:
import React, { Component } from 'react';
import addNumbers from "./components/addNumbers"
class App extends Component {
constructor() {
super()
this.state = {
value1: 10,
value2: 3,
sum: 13
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
//first setState call works fine
this.setState({[event.target.name]: event.target.value})
//call addNumbers function
const sum = addNumbers(this.state.value1, this.statevalue2)
//this second setState() call will lag by one step
this.setState({sum: sum})
console.log(newBarData)
}
render() {
return (
<div>
<form>
<input name="value1" type="number" placeholder="10" onBlur={this.handleChange} />
<input name="value2" type="number" placeholder="3" onBlur={this.handleChange} />
</form>
</div>
);
}
}
export default App;
会发生什么:第二个setState()
调用将不会生效,除非我在页面上进行了 second 更改。这是一个common issue,但我不确定如何解决。我希望它能够在用户更新表单后立即进行处理。在实际的用例中,将基于用户输入的值进行一些计算,然后在图表(plotly.js)上可视化,并且我希望能够在每次输入字段更改后更新图表“实时”。
答案 0 :(得分:1)
您可以使用currying在一段代码中创建不同的处理程序(请参阅:makeHandleChange
)。然后,您可以使用componentDidUpdate
检查输入值是否已更改以更新总和状态值。
import React, { Component } from 'react';
import addNumbers from "./components/addNumbers"
class App extends Component {
state = {
value1: 10,
value2: 3,
sum: 13
}
componentDidUpdate(lastProps, lastState) {
const valueChanged = this.state.value1 !== lastState.value1 || this.state.value2 != lastState.value2
if (valueChanged) {
const sum = addNumbers(this.state.value1, this.state.value2)
this.setState({ sum })
}
}
makeHandleChange = id => ({ target: { value } }) => {
this.setState({
[`value${id}`]: value
})
}
render() {
return (
<div>
<form>
<input name="value1" type="number" placeholder="10" onBlur={this.makeHandleChange(1)} />
<input name="value2" type="number" placeholder="3" onBlur={this.makeHandleChange(2)} />
<div>the sum is: {this.state.sum}</div>
</form>
</div>
);
}
}
export default App;