【问题标题】:Is it possible to use redux and axios in react component library?是否可以在 react 组件库中使用 redux 和 axios?
【发布时间】:2020-06-26 08:14:35
【问题描述】:

我正在 React 中创建一个页面。让我们说例如。 “联系我们”页面。这整个组件必须是可重用的。以便其他团队可以按原样使用它。这个组件将有自己的 redux store 和使用 axios 的 api 调用。

我想确认的是,如果我将这个“联系我们”模块导出为 npm 包,它是否适用于其他团队?为什么我问这个是因为其他团队项目将有自己的 redux 存储和 axios 实例。而且我认为我们可以在一个应用程序中只有一个 redux 商店,也许还有一个 axios 拦截器(虽然我对 axios 的看法可能是错误的)

谁能帮帮我,在这种情况下可以做些什么?有一件事是我必须将整个组件导出为 npm 包。

【问题讨论】:

  • 如果你正在构建一个组件库,我建议使用虚拟组件,接收redux props,然后你可以在实际项目中使用它们并在项目。
  • @JeanAguilar 你在推荐这样的东西吗:redux.js.org/recipes/isolating-redux-sub-apps
  • 我只是添加一个答案来澄清,你提供的隔离链接也是一个很好的例子,但我发布的那个避免了你的库中的 redux 和 axios 依赖项。

标签: reactjs npm redux react-redux axios


【解决方案1】:

我将在这里回答以提供更多详细信息: 假设您的组件如下所示:

关于我们:

import React, { Component } from "react";
import PropTypes from "prop-types";

export class AboutUs extends Component {
   componentDidMount() {
    const { fetchData } = this.props;
    fetchData();
   }

   render() {
    const { data, loading, error } = this.props;
    if (loading) return <p>Loading</p>;
    if (error) return <p>{error}</p>;
    return (
      // whatever you want to do with the data prop that comes from the fetch.
    )
   }
}

AboutUs.defaultProps = {
 error: null,
};

// Here you declare what is needed for your component to work.
AboutUs.propTypes = {
 error: PropTypes.string,
 data: PropTypes.shape({
  id: PropTypes.number,
  name: PropTypes.string,
 }),
 fetchData: PropTypes.func.isRequired,
 loading: PropTypes.bool.isRequired,
};

这个组件只需要几个 props 就可以工作,而 fetchData 函数将是任何 redux 操作的调度。

因此,在将要使用组件库的其中一个应用程序中,假设它们有自己的商店,您可以执行类似的操作。

在您计划使用 AboutUs 组件的组件中。

import React from "react";    
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
// this is the action that performs the data fetching flow.
import { fetchAboutUs } from "redux-modules/aboutUs/actions";
// The component that is above
import { AboutUs } from "your-component-library";

const mapDispatchToProps = dispatch => {
 return bindActionCreators(
  {
   fetchData: fetchDashboard,
  },
  dispatch
 );
};

const mapStateToProps = state => ({
 loading: state.aboutUsReducer.loading,
 error: state.aboutUsReducer.error,
 data: state.aboutUsReducer.data,
});

const ReduxAboutUs = connect(
 mapStateToProps,
 mapDispatchToProps
)(AboutUs);

// Use your connected redux component in the app.
const SampleComponent = () => {
 return <ReduxAboutUs />
}

这确保您的组件可以在没有 redux 的情况下开箱即用,因为您可以在没有 redux 依赖项的情况下显式使用它,并且只需 传递 常规 props,它就会继续工作。此外,如果您有不同的应用程序要使用它,您将可以控制要使用商店的哪个部分来为该组件注入 props。 Proptypes 在这里非常有用,因为我们强制执行一些 props 以便让开发人员我们需要传递什么才能使组件正常工作。

【讨论】:

  • 我们需要为其他团队提供即插即用选项。就像用户需要在他们的应用程序中写 一样。
  • @user10169731 您找到解决问题的方法了吗?谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 2022-01-27
  • 2019-01-15
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多