Javascript 渲染后,React组件成员重置为未定义
我有一个组件,它使用单独的客户端发出HTTP请求。在处理单击事件时尝试使用客户端时,调用Javascript 渲染后,React组件成员重置为未定义,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我有一个组件,它使用单独的客户端发出HTTP请求。在处理单击事件时尝试使用客户端时,调用this.client.getChannel()失败,因为this.client现在未定义 import*as React from'React'; 从“../modules/Client”导入客户端,{Channel}; 从“../modules/UI”导入{Container,Grid,GridItem,Placeholder}; 从“../components/ChannelsList”导入Chann
this.client.getChannel()
失败,因为this.client
现在未定义
import*as React from'React';
从“../modules/Client”导入客户端,{Channel};
从“../modules/UI”导入{Container,Grid,GridItem,Placeholder};
从“../components/ChannelsList”导入ChannelsList;
从“../components/Loading”导入加载;
接口道具{}
界面状态{
频道?:频道,
频道:频道[],
加载:布尔值
}
导出默认类ChannelsPage扩展React.Component{
公共客户端:客户端=新客户端();
建造师(道具:道具){
超级(道具);
此.state={
频道:[],
加载:正确
}
this.onChannelSelected.bind(this);
}
公共组件didmount(){
this.client.getChannels()//这可以工作:)
。然后((对象:频道[])=>{
这是我的国家({
通道:对象,
加载:错误
});
});
}
已选择公共频道(事件:任意,频道:频道){
this.client.getChannel(channel)//这不起作用,this.client未定义
.然后((对象:频道)=>{
this.setState({channel:object});
});
}
公共渲染(){
返回(
渠道
{this.state.loading?:}
{this.state.channel?{this.state.channel.uid}:选择一个频道以查看详细信息}
)
}
}
我不明白为什么这个。客户端在渲染后被设置为未定义。我想保留this.client
,只要组件处于活动状态,就可以发出任何HTTP请求,特别是因为客户端为我处理缓存响应
为什么在调用onChannelSelected
之前,this.client
被设置为undefined,有没有办法保存它?像这样更改onChannelSelected函数
public onChannelSelected = (event: any, channel: Channel) => {
this.client.getChannel(channel) // THIS DOES NOT WORK, this.client is undefined
.then((object: Channel) => {
this.setState({ channel: object });
});
}
或更改构造函数中的声明
this.onChannelSelected = this.onChannelSelected.bind(this);
this.onChannelSelected.bind(this)
应该是this.onChannelSelected=this.onChannelSelected.bind(this)代码>
this.onChannelSelected = this.onChannelSelected.bind(this);