【问题标题】:How is the key/label inferred in react native's setState?在 react native 的 setState 中如何推断键/标签?
【发布时间】:2017-08-07 18:45:30
【问题描述】:

我在浏览 React Native Autocomplete Input example 时遇到了一个经典的 this.setState 调用,它没有合并到带有标签的对象中。

  constructor(props) {
    super(props);
    this.state = {
      films: [],
      query: ''
    };
  }

  componentDidMount() {
    fetch(`${API}/films/`).then(res => res.json()).then((json) => {
      const { results: films } = json;
      this.setState({ films });
    });
  }

我期待 this.setState 调用看起来像

this.setState({ films: films });

说明这种语法糖是允许的代码/文档在哪里?这是纯 JavaScript 功能还是 React 功能?

相关研究

这感觉类似于object decomposition,但“颠倒了”。

我还仔细检查了 API 调用确实返回了一个类似的数组

"results": [ ... ] 

所以它不像this.setState({ films }); 实际上具有this.setState({ films: actual_object }); 的形式。

【问题讨论】:

标签: javascript react-native syntax ecmascript-6


【解决方案1】:

来自Object literals shorthand

this.setState({ films });
// is the same as:
this.setState({ films: films });

有关语法糖,另请参阅 http://es6-features.org/#PropertyShorthand

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多