javascript - 无法在 axios 回调 React Native 中访问正确的 this 上下文

标签 javascript reactjs react-native react-redux axios

我能够在 signInWithEmail 函数中访问正确的 this 上下文,但是 axios 回调函数中的 this 上下文是未定义。我可以使用 this.props.signInUser 在组件渲染中调用用户操作 SignInUser。但我想根据 api 响应来调用它。

这是我的组件中的代码

import React, { Component } from 'react';
import { View, Text, StyleSheet, Button, TextInput } from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { signInUser } from "../actions/UserActions"
import API from "../api/config";

class LoginForm extends Component {
    constructor(props) {
        super(props);
        console.log(props)
        this.state = { username: '', password: '' };
        this.signInWithEmail = this.signInWithEmail.bind(this);
    }

    signInWithEmail(username, pass) {
        console.log(this.props); // correct context here
        API.post('/token/', {
            username: username,
            password: pass
        }).then(function (response) {
            console.log(response.data);
            console.log(this.props); // undefined here
        }).catch(function (error) {
            // Show error or redirect
            console.log(error);
        });
}

    render() {
        return (
            <View>
                <Text>access: {this.props.userState.accessToken}</Text>
                <Text>refres: {this.props.userState.isSignout.toString()}</Text>
                <Text>username: {this.state.username}</Text>
                <Text>password: {this.state.password}</Text>
                <Text style={styles.inputLabel}> Username </Text>
                <TextInput
                    style={styles.input}
                    autoCapitalize="none"
                    onChangeText={(username) => this.setState({ username })}
                    value={this.state.username}
                />
                <Text style={styles.inputLabel}> Password </Text>
                <TextInput
                    style={styles.input}
                    secureTextEntry
                    onChangeText={(password) => this.setState({ password })}
                    value={this.state.password}
                />
                <Button title="Sign in with email" onPress={() => this.signInWithEmail(this.state.username, this.state.password)} />
                {/* <Button title="Sign in with email" onPress={() => this.props.signInUser("dummy-token", "dummy-refresh")} /> */}
            </View>
        );
    }
};

const styles = StyleSheet.create({
    label: {
        fontSize: 16,
        fontWeight: 'normal',
        marginBottom: 48,
        borderColor: "#FFF222"
    },
    divider: {
        borderBottomColor: '#000000',
        borderBottomWidth: 1,
        marginVertical: 10,
    },
    input: {
        backgroundColor: '#F0EEEE',
        height: 40,
        borderRadius: 5,
        marginBottom: 10,
        fontSize: 18
    },
    inputLabel: {
        fontSize: 18,
        fontWeight: "bold"
    }
});

const mapStateToProps = (state) => {
    const { userState } = state
    return { userState }
}

const mapDispatchToProps = dispatch => (
    bindActionCreators({
        signInUser,
    }, dispatch)
);

export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);

最佳答案

您可以在 then 回调中使用箭头函数 (=>)。在箭头函数内部,Context (this) 不会自动更改。试试这个:

API.post('/token/', {
        username: username,
        password: pass
    }).then(response => {
        console.log(response.data);
        console.log(this.props);
    }).catch(error => {
        console.log(error);
    });

注意在 Simple 函数内部(您用作 .then() 回调)Context(此)将是全局/窗口!

关于javascript - 无法在 axios 回调 React Native 中访问正确的 this 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60794148/

相关文章:

javascript - JSON.parse : expected ',' or '}' after property value in object

javascript - 如何在一个页面上托管六个以上的 html5 视频播放器?

react-native - React Navigation 5 的标题问题

react-native - Victory Native 饼图动画

javascript - React - 无法访问传递的函数

javascript - AJAX 请求在 HTTP_STREAM_PARSER_READ_HEADERS 之后被取消

javascript - jQuery 正在通过 XHR 再次加载我的根路由和所有脚本

javascript - 将 .NET Core 环境传递给 React.JS 应用程序

javascript - Jest 测试失败 : "Window is not defined"

javascript - react-redux 嵌套组件不是父组件中的 ReactClass?