如何在 React Native 中使用表单输入数据作为 axios 请求的输入?
How to use form input data as input for axios request in react native?
我需要有关如何使用输入表单中的文本作为本机 axios 请求输入的建议和帮助。
现在我正在向我的应用程序添加一个 SignIn
屏幕。要为我的应用检索任何 API,需要令牌。之前,我只是使用 redux 制作了一个动作文件来获取令牌并将其存储在 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
按钮时,根本没有结果。甚至控制台日志也没有出现。如果没有可以参考的console log,我不知道该如何解决这个问题。
如您所见,要获得令牌,email
和 password
,以及 'role' 的硬编码值,需要与 axios.post
一起传递] 要求。我希望如果请求成功,它会将用户导航到 Home
屏幕,如果不成功,它将再次将用户导航到 SignIn
屏幕。
我的问题是,如果我想使用表单输入中的数据或文本与 axios
请求一起传递,我是否在正确的轨道上使用此代码?如果没有,请通过分享您的建议来帮助我。
谢谢。
使用 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
从组件 props 中的 redux store 获取状态
function mapStateToProps(state) {
return { isLoggedIn: state.isLoggedIn } // accessed by this.props.isLoggedIn in your component
}
export default connect(mapStateToProps)(SignInScreen)
我需要有关如何使用输入表单中的文本作为本机 axios 请求输入的建议和帮助。
现在我正在向我的应用程序添加一个 SignIn
屏幕。要为我的应用检索任何 API,需要令牌。之前,我只是使用 redux 制作了一个动作文件来获取令牌并将其存储在 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
按钮时,根本没有结果。甚至控制台日志也没有出现。如果没有可以参考的console log,我不知道该如何解决这个问题。
如您所见,要获得令牌,email
和 password
,以及 'role' 的硬编码值,需要与 axios.post
一起传递] 要求。我希望如果请求成功,它会将用户导航到 Home
屏幕,如果不成功,它将再次将用户导航到 SignIn
屏幕。
我的问题是,如果我想使用表单输入中的数据或文本与 axios
请求一起传递,我是否在正确的轨道上使用此代码?如果没有,请通过分享您的建议来帮助我。
谢谢。
使用 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
从组件 props 中的 redux store 获取状态function mapStateToProps(state) {
return { isLoggedIn: state.isLoggedIn } // accessed by this.props.isLoggedIn in your component
}
export default connect(mapStateToProps)(SignInScreen)