简体   繁体   English

最好在 componentDidMount 或 componentWillMount 上执行 API 调用吗?

[英]Is it best to perform an API call on componentDidMount or componentWillMount?

I am trying to figure out what is the best way to perform an api call.我试图找出执行 api 调用的最佳方式。 I need to get the data when the component loads and not on any onClick/onPress method.我需要在组件加载时获取数据,而不是在任何 onClick/onPress 方法上。 This is the api call using fetch:这是使用 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);

The call will be perform here:调用将在此处执行:

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;

And I was also wondering if there is a way to make that call on an functional/stateless component?而且我还想知道是否有办法在功能/无状态组件上进行调用?

componentWillMount() is invoked just before mounting occurs. componentWillMount()在挂载发生之前被调用。 It is called right before render(), so by the time you get the data, the render() has already been called, your component should be able to render without any data.它在 render() 之前被调用,因此当您获取数据时,render() 已经被调用,您的组件应该能够在没有任何数据的情况下进行渲染。

It's recommended on the React Docs to fetch the data in componentDidMount() . React Docs 推荐在componentDidMount()获取数据。

Avoid introducing any side-effects or subscriptions in this method.避免在此方法中引入任何副作用或订阅。 For those use cases, use componentDidMount() instead.对于这些用例,请改用 componentDidMount()。

componentWillMount will be marked as “legacy”. componentWillMount将被标记为“legacy”。 it still works, but not recommended.它仍然有效,但不推荐。

Note笔记

This lifecycle was previously named componentWillMount.这个生命周期以前被命名为 componentWillMount。 That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.该名称将继续有效,直到版本 17。使用 rename-unsafe-lifecycles codemod 自动更新您的组件。

check this to see how to fetch data in a functional component .检查此以了解如何在功能组件中获取数据

Snippet from the link above :来自上面链接的片段:

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;

componentWillMount has been considered "legacy" since React 16.3 and had "UNSAFE" prepended to the function name to make that point clear: https://reactjs.org/docs/react-component.html#unsafe_componentwillmount and it will be removed altogether in an upcoming release of React (17.0). componentWillMount自 React 16.3 以来一直被认为是“遗留的”,并且在函数名称前加上了“UNSAFE”以明确这一点: https : //reactjs.org/docs/react-component.html#unsafe_componentwillmount它将在即将发布的 React (17.0)。 You can read more about this in the React blog but the key quote is probably:您可以在React 博客中阅读更多相关内容,但关键引用可能是:

[componentWillMount] is problematic for both server rendering (where the external data won't be used) and the upcoming async rendering mode (where the request might be initiated multiple times). [componentWillMount] 对于服务器渲染(不会使用外部数据)和即将到来的异步渲染模式(请求可能会多次发起)都是有问题的。

Therefore to keep your component working you should perform data fetching in componentDidMount .因此,为了让您的组件正常工作,您应该在componentDidMount执行数据获取。

To do this in a functional component, you may be able to use the new React feature of " Hooks ".要在功能组件中执行此操作,您可以使用“ Hooks ”的新 React 功能。 This enables the use of some state-mutating features of class components in functional components.这使得可以在功能组件中使用类组件的一些状态变异特性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 何时使用componentWillMount而不是componentDidMount - when to use componentWillMount instead of componentDidMount API响应时调用componentDidMount - Call componentDidMount when API responds 我需要使用componentDidMount或componentWillMount - componentDidMount or componentWillMount which one I need to use 为什么addChangeListener应该在componentDidMount而不是componentWillMount? - Why should addChangeListener be in componentDidMount instead of componentWillMount? componentDidMount 或 componentWillMount 在 React-Native 中不起作用? - componentDidMount or componentWillMount not working in React-Native? 作为回应,在Render()之前执行API调用和重定向的最佳方法是什么? - In react, what is the best way to perform an API call and redirect before Render()? 在componentWillMount中调用componentWillReceiveProps吗? - Call componentWillReceiveProps in componentWillMount? React Native组件未使用componentWillMount或componentDidMount中的异步redux操作呈现 - React Native component not rendering with async redux action in componentWillMount or componentDidMount 在React中使用componentWillMount或componentDidMount生命周期函数进行异步请求 - Use componentWillMount or componentDidMount lifecycle functions for async request in React 多个 state 内的多个 api 调用 ReactJS 内的 componentDidMount - Multiple set state within multiple api call inside componentDidMount in ReactJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM