gpt4 book ai didi

javascript - React setState 不覆盖对象

转载 作者:行者123 更新时间:2023-12-03 00:42:39 25 4
gpt4 key购买 nike

当尝试使用 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
});
}

忽略作为字符串的对象类型(我必须在发布之前概括代码),属性类型正确匹配,但 setState 似乎没有更新 customer 对象。

我也尝试过类似的方法

this.setState({customer: newCustomer})

运气不好。

最佳答案

我猜您尚未将 this 绑定(bind)到您的 customerOnChange(event, field) 事件。尝试将其写为customerOnChange =(事件,字段)=> {。请参阅下面的代码片段。

作为一种替代方法,您可以在构造函数中绑定(bind) 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>

关于javascript - React setState 不覆盖对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53379470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com