访问应用程序其他部分的构造函数中声明的类变量(React) [英] Accessing class variable declared in constructor in other parts of the app (React)
问题描述
我目前正在学习 React-native.我正在关注 Pluralsight 教程,但不幸的是他的一些代码已经过时了.我有以下代码:
I'm currently learning React-native. I am following a Pluralsight tutorial but unfortunately some of his code is out of date. I have the following code:
import Expo from 'expo';
import React from 'react';
import TaskList from './TaskList';
import {
Component,
View,
Navigator,
Text
} from 'react-native';
class todo extends React.Component {
constructor(props,context){
super(props,context);
this.state ={
todos: [
{
task: 'Task1',
},
{
task: 'Task 2',
},
]
}
}
onAddStarted(){
this.nav.push({
name: 'taskform',
})
}
renderScene(route,nav){
switch(route.name){
case 'taskform':
return (
<Text>Add form comes here!</Text>
);
default:
return(
<TaskList onAddStarted={this.onAddStarted}
todos={this.state.todos}/>
);
}
}
render() {
return (
<Navigator initialRoute={{name: 'Tasklist'}}
ref={((nav)=> {
this.nav=nav;
})}
renderScene={this.renderScene}/>
);
}
}
Expo.registerRootComponent(todo);
我的问题是:
todos={this.state.todos}/>
如果我记录 this.state 它会出错并且状态未定义.如果我内联复制 todos 的内容,代码会编译,所以我知道它在范围界定方面存在一些问题,但我想我从根本上不明白如何正确地做到这一点.在我开始使用 Navigator 之前,我完全可以从构造函数中引用 this.state.
if i log this.state it errors and state is undefined. If i copy the content of todos inline the code compiles so I know its some problem with scoping but I guess I fundamentally don't understand how to do it properly. Before I started using Navigator I was able to reference this.state from the constructor absolutely fine.
如果有人可以帮助我理解,我会很高兴.
I would appericiate if someone could help me understand.
谢谢!
推荐答案
你需要给 renderScene 上下文,以便它可以访问 this 然后它的状态.为此,您可以在渲染函数中修改以下行:
You need to give renderScene context, so that it can access this and then its state. To do this you can amend the following line in the render function:
renderScene={this.renderScene}
到
renderScene={this.renderScene.bind(this)}
注意由于使用 bind 会生成一个新函数,这会降低性能(例如,如果您要渲染很多项目).所以一个常见的模式是在构造函数中进行绑定:
N.B. As using bind generates a new function this can degrade performance (for instance if you are rendering a lot of items). So a common pattern is to do the binding in the constructor:
this.renderScene = this.renderScene.bind(this);
如果您采用这种方法,您的渲染功能可以保持现在的状态.
If you take this approach your render function can stay like it is now.
这篇关于访问应用程序其他部分的构造函数中声明的类变量(React)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!