gpt4 book ai didi

javascript - 最好是对 componentDidMount 或 componentWillMount 执行 API 调用吗?

转载 作者:行者123 更新时间:2023-11-29 23:05:58 26 4
gpt4 key购买 nike

我正在尝试找出执行 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 Docs推荐在componentDidMount()中获取数据。

Avoid introducing any side-effects or subscriptions in this method. For those use cases, use componentDidMount() instead.

componentWillMount 将被标记为“legacy”。它仍然有效,但不推荐。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com