【问题标题】:React Native + TypeScript + asyncReact Native + TypeScript + 异步
【发布时间】:2018-05-02 01:12:24
【问题描述】:

我无法让这个组合起作用。我认为这特别是由于混合了 TypeScript?我的语法如here 所见,但我遇到了运行时问题。没有编译错误,但是当遇到 func 时,我得到:

this.foo 不是函数

export default class App extends Component<Props> {
    render() {
        return (
            <Button title="A Button" onPress={this.buttonPressed} />
        );
    }

    buttonPressed() {
        this.foo().then(movies => {
            console.log(movies);
        });
    }

    async foo() { 
        try {
            let response = await fetch('https://facebook.github.io/react-native/movies.json');
            let responseJson = await response.json();
            return responseJson.movies;
        } catch (error) {
            console.error(error);
        }
    }
}

【问题讨论】:

  • 当您将方法作为回调传递时,this 将不再引用类实例。你可能想take a look at this question
  • 哦,天哪,我知道这一点!下面回答。谢谢,我的脑袋已经很久没有接触过 React Native 了。

标签: typescript react-native


【解决方案1】:

正如CRice 所指出的,这仅仅是因为无法在匿名回调中访问this。可以通过以下方式解决:

onPress={() => this.buttonPressed(this)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多