【问题标题】:How to use form input data as input for axios request in react native?react-native - 如何使用表单输入数据作为axios请求的输入?
【发布时间】:2017-11-24 08:49:38
【问题描述】:

我需要关于如何在 react native 中使用输入表单中的文本作为 axios 请求的输入的建议和帮助。

现在我正在向我的应用程序添加一个SignIn 屏幕。要检索我的应用程序的任何 API,需要令牌。之前,我只是使用 redux 制作了一个 action 文件来获取令牌并将其存储在 reducer 中。

对于这种情况,我在登录时尝试使用表单输入中的email 和password 作为我检索令牌的数据。长话短说,这是我现在的代码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>
    );
}

我的actions/types

export const FETCH_TOKEN = 'fetch_token';

我的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;
    }
}

我运行这段代码,当我点击LogIn 按钮时,根本没有结果。甚至控制台日志也没有出现。如果没有可以参考的控制台日志,我不知道该如何解决这个问题。

如您所见,要获取令牌email 和password,以及“角色”的硬编码值,需要与axios.post 请求一起传递。我期待如果请求成功,它会将用户导航到Home 屏幕,如果没有,它将再次将用户导航到SignIn 屏幕。

我的问题是,如果我想使用表单输入中的数据或文本与axios 请求一起传递,我是否在正确的轨道上使用此代码?如果不是,请通过分享您的建议来帮助我。

谢谢。

【问题讨论】:

  • 是否有理由在 react-native 中使用 axios 而不是默认的 fetch ?
  • 我最初是从axios 开始的,由于我不太擅长javascript,所以我倾向于使用我学到的第一个使用axios 的示例。但如果您有除axios 以外的建议并使用redux,我很想知道

标签: javascript forms react-native axios


【解决方案1】:

使用 fetch 替换你的 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 */ )
});

也许将您的组件与 redux 连接以使用 this.props.dispatch 来调度操作而不是 asyn func:

从 redux 导入连接函数:

import { connect } from 'react-redux'

在文件末尾添加:

export default connect()(SignInScreen)

移除异步函数:

onButtonPress = () => { 

使用 this.props.dispatch 来调度操作:

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

您还可以使用 mapStateToProps 从组件道具中的 redux 存储中获取状态

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

export default connect(mapStateToProps)(SignInScreen)

【讨论】:

  • 您对this.props.dispatch 的建议帮助了我。我稍微修改了我的代码并添加了this.props.dispatch,而不是仅添加了dispatch。现在我可以在登录后使用保存的令牌在应用程序中执行其他一些请求。
猜你喜欢
  • 2020-12-01
  • 2020-07-21
  • 2021-07-04
  • 2020-07-29
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
相关资源
最近更新 更多