[英]React Component member resets to undefined after rendering
我有一个使用单独的客户端发出HTTP请求的组件。 在处理单击事件时尝试使用客户端时,对this.client.getChannel()
的调用失败,因为现在未定义this.client
。
import * as React from 'react';
import Client, { Channel } from '../modules/Client';
import { Container, Grid, GridItem, Placeholder } from '../modules/UI';
import ChannelsList from '../components/ChannelsList';
import Loading from '../components/Loading';
interface Props {}
interface State {
channel?: Channel,
channels: Channel[],
loading: boolean
}
export default class ChannelsPage extends React.Component<Props, State> {
public client: Client = new Client();
constructor(props: Props) {
super(props);
this.state = {
channels: [],
loading: true
}
this.onChannelSelected.bind(this);
}
public componentDidMount() {
this.client.getChannels() // THIS WORKS :)
.then((objects: Channel[]) => {
this.setState({
channels: objects,
loading: false
});
});
}
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 });
});
}
public render() {
return (
<Container>
<h1>Channels</h1>
<Grid>
<GridItem width={'1/3'}>
{ this.state.loading ? <Loading /> : <ChannelsList channels={ this.state.channels } onChannelSelected={ this.onChannelSelected } /> }
</GridItem>
<GridItem width={'2/3'}>
{ this.state.channel ? <p>{ this.state.channel.uid }</p> : <Placeholder>Select a channel to view details</Placeholder> }
</GridItem>
</Grid>
</Container>
)
}
}
我对于为什么在渲染之后将this.client
设置为undefined
感到困惑。 我想保留this.client
,只要该组件还可以发出任何HTTP请求,尤其是因为该客户端为我处理缓存响应时。
为什么是this.client
被设置为undefined被称为前onChannelSelected
,是有办法保护它?
像这样更改onChannel Selected函数
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.