简体   繁体   English

在React Native中,如何使用表单输入数据作为axios请求的输入?

[英]How to use form input data as input for axios request in react native?

I need suggestion and help on how to use text from input form as the input for axios request in react native. 我需要有关如何使用输入表单中的文本作为React Native中axios请求输入的建议和帮助。

Right now I am adding a SignIn screen to my app. 目前,我正在向我的应用添加“ SignIn屏幕。 To retrieve any API for my app, there is a need for token. 要为我的应用检索任何API,需要令牌。 Before, I just made a one action file using redux to fetch token and store it inside a reducer. 之前,我只是使用redux制作了一个动作文件来获取令牌并将其存储在reducer中。

For this case, I am trying to use email and password from form input while signing in as the data for me to retrieve the token. 在这种情况下,我尝试使用表单输入中的emailpassword ,同时登录以获取我的数据作为令牌。 Long story short, this is my code SignInScreen.js right now 长话短说,这是我的代码SignInScreen.js

import React, { Component, AsyncStorage } from 'react';
import { View, Text } from 'react-native';
import { FormLabel, FormInput, Button, Card } from 'react-native-elements';
import axios from 'axios';
import { FETCH_TOKEN } from '../actions/types';
import apiConfig from '../services/api/url_config';

class SignInScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loggedIn: null,
            email: '',
            password: '',
            error: '',
            loading: false
        };
    }

onButtonPress = () => async (dispatch) => {
    let email = this.state.email;
    let password = this.state.password;

    AsyncStorage.getItem('auth', (res) => {
        let TOKEN_URL = apiConfig.url + 'tokens';
        let auth = {};

        if (res === null) {
            auth = {};
        } else {
            auth.push({
                email: email,
                password: password,
                role: 'user'
            });

            console.log(auth);

            axios.post(TOKEN_URL, auth)
            .then((response) => {
                console.log(response.data.token);
                dispatch({ type: FETCH_TOKEN, payload: response.data.token });
                this.props.navigation.navigate('Home');
            })
            .catch((e) => {
                console.log(e);
                this.props.navigation.navigate('SignIn');
            });
        }
    });    
}


render() {
    return (
        <View>
            <Card>
                <FormLabel>Email</FormLabel>
                <FormInput 
                    placeholder="user@email.com"
                    value={this.state.email}
                    onChangeText={email => this.setState({ email })}
                />
            </Card>
            <Card>
                <FormLabel>Password</FormLabel>
                <FormInput 
                    secureTextEntry
                    placeholder="password"
                    value={this.state.password}
                    onChangeText={password => this.setState({ password })}
                />
            </Card>

            <Card>
                <Button 
                    title="Log In"
                    onPress={this.onButtonPress}
                />
            </Card>

        </View>
    );
}

My actions/types 我的actions/types

export const FETCH_TOKEN = 'fetch_token';

My tokenReducer.js 我的tokenReducer.js

import {
    FETCH_TOKEN
} from '../actions/types';

export default function tokenReducer(state = '', action) {
    switch (action.type) {
        case FETCH_TOKEN:
            return action.payload;
        default:
            return state;
    }
}

I run this code and when I click on LogIn button, there is no result at all. 我运行此代码,然后单击“ LogIn按钮,根本没有结果。 Even the console log too also did not appear. 甚至控制台日志也没有出现。 I do not know how should I troubleshoot this problem if there is no console log I can refer to. 如果没有可参考的控制台日志,我不知道该如何解决此问题。

As you can see, to get the token, email and password , as well as the hardcoded value for 'role', need to be pass alongside the axios.post request. 如您所见,要获得令牌, emailpassword以及“角色”的硬编码值,需要将其与axios.post请求一起传递。 I am expecting if the request is successful, it will navigate the user to the Home screen while if it not, it will navigate the user to the SignIn screen again. 我期待,如果请求是成功的,它会在用户导航到Home屏幕,而如果它不是,它会浏览用户的SignIn再次屏幕。

My question is, if I want to use the data or text from form input to be pass alongside axios request, am I on the right track with this code? 我的问题是,如果我想使用表单输入中的数据或文本与axios请求一起axios ,那么使用此代码是否在正确的轨道上? If it not, please help me by sharing your suggestion. 如果没有,请分享您的建议来帮助我。

Thank you. 谢谢。

Using fetch to replace your axios request : 使用访存替换axios请求:

fetch(TOKEN_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(auth),
  })
  .then(response => response.json())
  .then(responseData => /* responseData.token to access your token */ )
  .catch(err => /* Handle Error */ )
});

Maybe connect your component with redux to use this.props.dispatch to dispatch actions instead of asyn func : 也许将您的组件与redux连接起来,以使用this.props.dispatch而不是asyn func来调度动作:

import connect function from redux : 从redux导入连接功能:

import { connect } from 'react-redux'

Add at the end of your file : 在文件末尾添加:

export default connect()(SignInScreen)

Remove async func : 删除异步函数:

onButtonPress = () => { 

use this.props.dispatch to dispatch actions : 使用this.props.dispatch调度动作:

this.props.dispatch({ type: FETCH_TOKEN, payload: response.data.token });

You can also get state from redux store in your component props by using mapStateToProps 您还可以使用mapStateToProps从组件属性中的redux存储中获取状态

function mapStateToProps(state) {
  return { isLoggedIn: state.isLoggedIn } // accessed by this.props.isLoggedIn in your component
}

export default connect(mapStateToProps)(SignInScreen)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM