我将在这里回答以提供更多详细信息:
假设您的组件如下所示:
关于我们:
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 以便让开发人员我们需要传递什么才能使组件正常工作。