访问在应用程序其他部分的构造函数中声明的类变量(反应) [英] 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它错误并且状态未定义如果我以内联方式复制待办事项的内容,则代码会编译,因此我知道其范围界定方面的问题,但我想我从根本上不知道如何正确地做到这一点.在开始使用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 及其状态.为此,您可以在render函数中修改以下行:
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)}
NB (使用 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.
这篇关于访问在应用程序其他部分的构造函数中声明的类变量(反应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!