【问题标题】:react native - assigning state to const反应原生 - 将状态分配给 const
【发布时间】:2019-12-30 15:41:09
【问题描述】:

我从 react native 开始,当使用一个名为 react native paper 的库时,我遇到了一个语句,其中状态被分配给一个 const,如下所示。

import * as React from 'react';
import { Searchbar } from 'react-native-paper';

export default class MyComponent extends React.Component {
  state = {
    firstQuery: '',
  };

  render() {
    const { firstQuery } = this.state;
    return (
      <Searchbar
        placeholder="Search"
        onChangeText={query => { this.setState({ firstQuery: query }); }}
        value={firstQuery}
      />
    );
  }
}

'Render' 方法的开始,你可以看到 const { firstQuery } = this.state; 有人可以解释为什么将状态分配给名为“firstQuery”的常量,即使有原因,分配如何正确地将状态对象内的属性“firstQuery”映射到常量?

提前致谢。代码示例来自https://callstack.github.io/react-native-paper/searchbar.html#value

【问题讨论】:

    标签: javascript reactjs react-native react-native-paper


    【解决方案1】:

    该语法既不是 React 也不是 React Native。这只是 Javascript 的语法,称为解构。

    const { firstQuery } = this.state;
    

    等价于

    const firstQuery = this.state.firstQuery;
    

    只是一个简写的快捷语法,你看到 2 firstQuerys?人们只是不想在代码中重复,所以他们发明了它。


    请参阅下面的 vanilla javascript sn-p:

    const object = {
      name: 'Aby',
      age: 100,
    }
    
    const { name, age } = object;
    // instead of 
    // const name = object.name;
    
    console.log(name, age);
    console.log(object.name, object.age);
    
    //=========================================
    // imagine:
    const obj = {
      veryLongPropertyNameToType: 420
    }
    
    const { veryLongPropertyNameToType } = obj;
    // instead of
    // const veryLongPropertyNameToType = obj.veryLongPropertyNameToType;

    【讨论】:

      【解决方案2】:

      就像提到的另一个答案一样,它只是 JavaScript 语法,也就是解构。如果您感到困惑并希望只使用“vanilla”JavaScript 语法,可以查看以下内容。

      import * as React from 'react';
      import { Searchbar } from 'react-native-paper';
      
      export default class MyComponent extends React.Component {
        state = {
          firstQuery: '',
        };
      
        render() {
          return (
            <Searchbar
              placeholder="Search"
              onChangeText={query => { this.setState({ firstQuery: query }); }}
              value={this.state.firstQuery} // <<<<<<<<<<< LOOK HERE
            />
          );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-03-23
        • 2020-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-25
        • 1970-01-01
        相关资源
        最近更新 更多