[英]Why i cannot assign values to destructured object variables?
我的网站上有带有 onSubmit eventListener 的表单,因此当用户提交表单时,将执行 getCurrencyData 函数。 在 getCurrencyData 函数中,我正在检查用户是否输入了值,如果是,那么我将进行 apicall 并解构 generalCurrencyInfo 对象。 问题是我无法为解构的对象变量赋值。
class App extends Component {
constructor(props) {
super(props);
this.state = {
generalCurrencyInfo: {
fullName: undefined,
name: undefined,
imageUrl: undefined,
price: undefined,
error: false
}
}
}
getCurrencyData = async (e) => {
e.preventDefault();
const CURRENCYNAME = e.target.elements.currencyName.value.toUpperCase();
//Checks if currency name is not empty
if (CURRENCYNAME) {
const APICALL = await fetch(`url`);
const DATA = await APICALL.json();
let generalCurrencyInfo = {
fullName:undefined,
name: undefined,
imageUrl: undefined,
price: undefined,
error: false
}
//this destructuring doesn't work
let {fullName, name, imageUrl, price, error} =generalCurrencyInfo;
if (DATA.Message === "Success") {
fullName = DATA.Data[0].CoinInfo.FullName;
name = DATA.Data[0].CoinInfo.Name;
imageUrl = `url`;
price = "price";
error = false;
}
this.setState({
generalCurrencyInfo: generalCurrencyInfo
})
}
}
render() {
return (
);
}
}
您在这里创建了 5 个新变量:
let {fullName, name, imageUrl, price, error} =generalCurrencyInfo;
然后你改变了这个变量,但不是 generalCurrencyInfo 对象:
if (DATA.Message === "Success") {
fullName = DATA.Data[0].CoinInfo.FullName;
name = DATA.Data[0].CoinInfo.Name;
imageUrl = `url`;
price = "price";
error = false;
}
在这里你设置了 generalCurrencyInfo,什么没有改变:
this.setState({
generalCurrencyInfo: generalCurrencyInfo
})
这会很好:
this.setState({
fullName,
name,
imageUrl,
price,
error,
})
您可以将值重新分配给您的 generalCurrencyInfo 对象,因此无需解构:
// reassign values
if (DATA.Message === "Success") {
generalCurrencyInfo.fullName = DATA.Data[0].CoinInfo.FullName;
generalCurrencyInfo.name = DATA.Data[0].CoinInfo.Name;
generalCurrencyInfo.imageUrl = `url`;
generalCurrencyInfo.price = "price";
generalCurrencyInfo.error = false;
}
// or using the spread operator
if (DATA.Message === "Success") {
generalCurrencyInfo = {
...generalCurrencyInfo,
fullName: DATA.Data[0].CoinInfo.FullName,
name: DATA.Data[0].CoinInfo.Name,
imageUrl: `url`,
price: "price",
error: false,
};
}
但是,如果您访问此页面并希望了解如何将值重新分配给已解构的对象,您可能需要查看以下问题: 是否有可能对现有对象进行解构? (JavaScript ES6)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.