【发布时间】: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