渲染后,React Component成员重置为undefined

时间:2018-04-24 03:00:47

标签: javascript reactjs typescript

我有一个使用单独客户端发出HTTP请求的组件。在处理点击事件时尝试使用客户端时,对this.client.getChannel()的调用失败,因为this.client现在未定义。

enter image description here

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.clientonChannelSelected中被调用之前被设置为未定义,是否有保留它的方法?

1 个答案:

答案 0 :(得分:1)

更改onChannel选择的功能,如下

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);