简体   繁体   English

React-Redux 存储或将 props 中的 api 传递给组件,这是更好的方法

[英]React-Redux store or Passing the api in props to the components which is better way

I am just going through a confusion so far.到目前为止,我只是在经历一个混乱。 I am developing a React application for that some amount of API call is required.我正在开发一个需要一定数量的 API 调用的 React 应用程序。 so I just confused with whether calling the API in the component and passing the dats by props to the required components or Using redux thunk to fetch the api's and store in to a React store and fetching the required data by dispatching the action when ever it required.所以我只是混淆了是否在组件中调用 API 并通过 props 将 dats 传递给所需的组件,或者使用 redux thunk 来获取 api 并存储到 React 存储中并通过在需要时分派动作来获取所需的数据.

Suggestions will be appreciable :)建议将是可观的:)

I strongly recommend not to use React-Redux.我强烈建议不要使用 React-Redux。 Here are the reasons以下是原因

  1. Why should you add a library in your application just for passing states为什么要在应用程序中添加一个库只是为了传递状态
  2. Redux comes with code of overhead(writing actions, etc) Redux 带有开销代码(编写操作等)
  3. React's Context API can solve your problem (which is already available in react library) React 的 Context API 可以解决你的问题(react 库中已经提供了)
  4. React Composition is another way of passing states to child components. React Composition 是另一种将状态传递给子组件的方式。
  5. Redux has maintenance overhead as well. Redux 也有维护开销。

All in all, your React can manage all your state communication problems alone.总而言之,您的 React 可以单独管理您所有的状态通信问题。 You don't need another library for state management.您不需要另一个用于状态管理的库。

Note: Whenever I say React, I mean React newer versions.注意:每当我说 React 时,我的意思是 React 的较新版本。 React 16.8+反应 16.8+

Calling the API is surely gonna be done in the component.调用 API 肯定会在组件中完成。 Like so:像这样:

const Component = () => {
  useEffect(() => {
    const fn = async () => {
      await apiCall()
    }
    fn()
  }, [])
}

But your question resides on where you should store it.但是你的问题在于你应该在哪里存储它。

This is simple:这很简单:

  1. If the data you are getting are gonna be used across the whole app, then Redux is a great option.如果您获得的数据将在整个应用程序中使用,那么 Redux 是一个不错的选择。 It also comes with data persistence with very little effort using redux-persist ( https://github.com/rt2zz/redux-persist ) so it's not only to have a global object you can access.它还带有使用redux-persist ( https://github.com/rt2zz/redux-persist ) 的数据持久性,因此它不仅具有您可以访问的全局对象。

Features:特征:

a.一种。 Persistance b.持久性 B. Global state accesible anywere c.可访问的全局状态 c. Enhanced debugging with Redux dev tools使用 Redux 开发工具增强调试

  1. If you only want to avoid prop drilling then React.Context is a good option如果你只想避免prop drilling那么React.Context是一个不错的选择
  2. If you are only drilling 2 or 3 leves with your props, just don't overkill it using a Context如果您只使用道具drilling 2 或 3 层,请不要使用Context过度使用它

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM