为什么我不能为结构化对象变量赋值?

时间:2019-04-12 12:35:31

标签: javascript reactjs destructuring

我的网站上有onSubmit eventListener表单,因此当用户提交表单时,将执行getCurrencyData函数。在getCurrencyData函数内部,im检查用户是否输入了值,如果是,则使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 (

    );
  }
}

2 个答案:

答案 0 :(得分:1)

您在此处创建了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,
})

答案 1 :(得分:0)

您只需将值重新分配给您的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,
  };
}

但是,如果您登陆此页面以查找如何将值重新分配给已分解的对象,则可能需要检查以下问题:Is it possible to destructure onto an existing object? (Javascript ES6)