gpt4 book ai didi

javascript - React Component 成员在渲染后重置为未定义

转载 作者:行者123 更新时间:2023-12-03 02:01:34 25 4
gpt4 key购买 nike

我有一个使用单独的客户端发出 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 请求,特别是因为客户端为我处理缓存响应。

为什么在 onChannelSelected 中调用 this.client 之前被设置为未定义,有没有办法保留它?

最佳答案

像这样更改 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);

关于javascript - React Component 成员在渲染后重置为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49992804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com