gpt4 book ai didi

javascript - React Native - 将状态分配给 const

转载 作者:行者123 更新时间:2023-11-28 12:12:09 24 4
gpt4 key购买 nike

我从 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

最佳答案

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

const { firstQuery } = this.state;

相当于

const firstQuery = this.state.firstQuery;

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

<小时/>

请参阅下面的普通 javascript 片段:

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;

关于javascript - React Native - 将状态分配给 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59533314/

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