我有一个登录功能,我在其中设置了令牌,该令牌已保存在redux存储中,然后,在登录发生后,我需要再次调用api,它将向主屏幕提供数据。但是为了进行呼叫,我需要令牌。
这是我需要拨打电话的主屏幕组件:
// imports
import styles from '../../styles/HomeScreenStyles';
import { passengersDataAction } from './actions/homeScreen';
class HomeScreen extends Component {
static navigationOptions = {
header: null,
};
componentDidMount() {
this.GetPassengersData();
}
GetPassengersData = async () => {
// userToken is coming from the store
const { passengersDataActionHandler, userToken } = this.props;
if (userToken && userToken !== null) {
try {
const response = await fetch(
'http://myAPI/public/api/getPassengers',
{
method: 'POST',
headers: {
Authorization: `Bearer ${userToken}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
},
);
const responseJson = await response.json();
passengersDataActionHandler(responseJson.success.data);
} // catch ...
}
};
render() {
return <TabView style={styles.container} />;
}
}
// export
在GetPassengersData
被称为userToken
的时候还不存在,所以我的请求直接转到catch错误回调。
我该如何处理?
编辑: 我上面放置的API调用是我需要令牌的调用。
致电获取登录数据:
import { Alert, AsyncStorage } from 'react-native';
import { has } from 'lodash';
import PropTypes from 'prop-types';
const FetchLoginData = async (
username,
password,
navigation,
userTokenActionHandler,
) => {
try {
const response = await fetch(
'http://myAPI/public/api/driverlogin',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ email: username, password }),
},
);
const responseJson = await response.json();
if (has(responseJson, 'error')) {
Alert.alert('Error', 'Please check your credentials.');
} else {
// HERE I SET THE TOKEN
await AsyncStorage.setItem('userToken', responseJson.success.token);
userTokenActionHandler(responseJson.success.token);
navigation.navigate('App');
}
} catch (error) {
Alert.alert(
'Error',
'There was an error with your request, please try again later.',
);
}
};
FetchLoginData.propTypes = {
navigation: PropTypes.shape({}).isRequired,
userTokenActionHandler: PropTypes.func.isRequired,
};
export default FetchLoginData;
答案 0 :(得分:0)
您可以在这里拨打第二个电话:
try {
const response = await fetch(
'http://myAPI/public/api/getPassengers',
{
method: 'POST',
headers: {
Authorization: `Bearer ${userToken}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
},
);
const responseJson = await response.json();
passengersDataActionHandler(responseJson.success.data);
// **put second call here you have token here send it to second api call**
}