我正在尝试找出执行 api 调用的最佳方法。我需要在组件加载时获取数据,而不是在任何 onClick/onPress 方法上获取数据。 这是使用 fetch 的 api 调用:
import { Alert, AsyncStorage } from 'react-native';
import { has } from 'lodash';
import PropTypes from 'prop-types';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { passengersDataAction } from '../screens/HomeScreen/actions/homeScreen';
const GetPassengersData = async (
username,
password,
navigation,
passengersDataActionHandler,
) => {
try {
const response = await fetch(
'http://myAPI/public/api/getPassengers',
{
method: 'POST',
headers: {
Authorization: `Bearer ${868969}`,
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 {
await AsyncStorage.setItem('userToken', responseJson.success.token);
passengersDataActionHandler(responseJson.success.token);
navigation.navigate('App');
}
} catch (error) {
Alert.alert(
'Error',
'There was an error with your request, please try again later.',
);
}
};
GetPassengersData.propTypes = {
navigation: PropTypes.shape({}).isRequired,
passengersDataActionHandler: PropTypes.func.isRequired,
};
export default compose(
connect(
store => ({
userToken: store.signinScreen.userToken,
passengersData: store.homeScreen.passengersData,
}),
dispatch => ({
passengersDataActionHandler: token => {
dispatch(passengersDataAction(token));
},
}),
),
)(GetPassengersData);
调用将在此处执行:
class AllPassengers extends Component {
compo
render() {
return (
<ScrollView>
<View style={{ height: 50 }} />
<View
style={[
tabViewStyles.container,
{ alignItems: 'center', justifyContent: 'center' },
]}
>
<Text style={{ fontWeight: 'bold' }}>
Select passengers to start your route
</Text>
<View style={{ height: 50 }} />
<PassengersCircle />
</View>
<AllPassengersList />
</ScrollView>
);
}
}
export default AllPassengers;
我还想知道是否有办法在功能/无状态组件上进行该调用?
最佳答案
componentWillMount()在安装发生之前调用。它在 render() 之前调用,因此当您获取数据时,render() 已经被调用,您的组件应该能够在没有任何数据的情况下渲染。
React 文档建议在 componentDidMount()
中获取数据。
Avoid introducing any side-effects or subscriptions in this method. For those use cases, use componentDidMount() instead.
componentWillMount
将被标记为“旧版”。它仍然有效,但不推荐。
Note
This lifecycle was previously named componentWillMount. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.
检查这个看看 how to fetch data in a functional component .
上面链接的片段:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState({ hits: [] });
useEffect(async () => {
const result = await axios(
'http://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
});
return (
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
);
}
export default App;
关于javascript - 最好在 componentDidMount 或 componentWillMount 上执行 API 调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54777199/