当尝试使用setState更新客户年龄时,该对象会在setState之前发生突变,但是setState不会更新现有对象。
customerOnChange(event, field) {
//Customer age right now is 80
var customer = { ...this.state.customer };
customer.age = "14";
console.log('The age of the customer is ', customer.age) //This shows up correctly
this.setState({
customer
},
() => {
console.log(this.state.customer.age) //Customer age still 80
});
}
忽略对象类型为String(我必须在发布之前对代码进行泛化),属性类型正确匹配,但是setState似乎没有更新customer
对象。
我也尝试过类似的方法
this.setState({customer: newCustomer})
没有运气。
答案 0 :(得分:1)
我猜您尚未将this
绑定到您的customerOnChange(event, field)
事件。尝试写成
customerOnChange = (event, field) => {
。请参见下面的代码段。
或者,可以将this
绑定到构造函数中(如果有的话)。像这样:
constructor(props){
super(props);
this.state={
customer: { age: 80 }
}
this.customerOnChange = this.customerOnChange.bind(this);
}
class Thingy extends React.Component {
state = {
customer: {
age: "80"
}
}
customerOnChange = (event, field) => {
//Customer age right now is 80
const customer = { ...this.state.customer};
customer.age = event.target.value;
console.log('The age of the customer is ', customer.age) //This shows up correctly
this.setState({
customer
},
() => {
console.log(this.state.customer.age) //Customer age still 80
});
}
render() {
const {age} = this.state.customer;
return (
<div >
<input type="number" value={age} onChange={this.customerOnChange} />
<p>Customers Age:{age}</p>
</div>
);
}
}
// Render it
ReactDOM.render( <
Thingy title = "I'm the thingy" / > ,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>