javascript - 在渲染函数之后写变量和在构造函数中写“变量的this.name”有什么区别?
问题描述
像这样在渲染函数之后编写变量有什么区别:
render() {
var headers=[
{ key: 'userId', label: 'User ID' },
{ key: 'id', label: 'ID' },
{ key: 'title', label: 'Title' },
{ key: 'body', label: 'Body' }
];
return (
并在构造函数中写入“this.name of variable”,如下所示:
class App extends Component {
constructor(props) {
super(props);
this.state = {
users: []
};
this.headers = [
{ key: 'userId', label: 'User ID' },
{ key: 'id', label: 'ID' },
{ key: 'title', label: 'Title' },
{ key: 'body', label: 'Body' }
];
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
return response.json();
}).then(result => {
this.setState({
users:result
});
});
}
render() {
除了当我在第一个中调用它时我写 { headers } 而在第二个中我写 {this.headers}
注意:这里不是var vs this,是create-react-app中主app类的结构及其与前面代码写入位置的关系。
解决方案
this.someName 将成为“this”值的字段,在您的情况下,App 类。因此,它在整个 App 类中都可用,例如在渲染方法或任何其他实例方法中,例如 componentDidMount 或 foo()。
相反,如果你在渲染函数中声明变量,那么它的作用域是渲染函数,即它不会在实例方法中可用,例如componentDidMount。
如果您在 render 方法中定义变量,那么它只是一个方法中的变量,因此它将在每次调用 render 函数时被实例化,如果没有充分的理由产生额外的开销,这可能会很昂贵,然后在此声明变量将是一个明智的选择。
唯一想到的另一件事是更改类字段的值不会使渲染排队,而如果在 React 组件类的状态对象中定义给定值,那么这将触发新的渲染。
PS - 不是 100% 清楚你在问什么。
推荐阅读
- laravel-5.7 - “语法错误或访问冲突” - 从 Schema:: 外观迁移,但语句执行没有错误
- c# - 从 c# 了解 docker linux 容器中是否存在目录
- c++ - 如何解耦 C++ 项目标头依赖项?
- usb - 无法挂载 ext4 格式的 USB
- php - Laravel7 在刀片文件中使用函数
- python - 在单独的线程中启动异步事件循环并使用队列项
- javascript - TS 中“每个”函数的 TypeError
- php - 数据库中的json数据同步
- ruby-on-rails - Rails:在没有模型或数据库连接的情况下使用 sanitize_sql_for_conditions
- apache-arrow - Arrow Java ListVector writeBatch 和读取获取空列表