在 React Redux 应用中使用 PropTypes 可以帮助您捕获运行时错误。但是当您将 Redux 追加到应用程序中时,这变得更加困难,因为您使用的所有组件都必须通过 props 访问 Redux 存储。redux-proptypes-pack 是一个包,可以为 Redux 属性定义 PropTypes。
安装
您可以使用 npm 安装 redux-proptypes-pack:
npm install redux-proptypes-pack
如何使用
首先,导入 PropTypes 和 createReduxPack:
import { PropTypes } from 'react'; import { createReduxPack } from 'redux-proptypes-pack';
然后定义您要使用 PropTypes 的 Redux 属性:
const propTypes = { counter: PropTypes.number.isRequired };
接下来,使用 createReduxPack 创建一个具有映射对象的函数,该映射对象定义了您将用于 PropTypes 的 Redux 属性:
const reduxPropTypes = createReduxPack({ counter: state => state.counter });
最后,将 Redux 属性包装在 PropTypes 上:
const propTypes = { ...reduxPropTypes, someOtherProp: PropTypes.string.isRequired };
这就是它!现在,您可以在组件中使用PropTypes,并确保使用的Redux属性具有正确的类型。
示例代码
-- -------------------- ---- ------- ------ ----- ---- -------- ------ - --------- - ---- -------- ------ - ------- - ---- -------------- ------ - --------------- - ---- ----------------------- ----- --------- - - -------------------- -------- ----- -- ------------- --- -------------- --------------------------- -- ----- ------- ------- --------------- - -------- - ----- - ------- - - ----------- ------ - ----- ---------------- ---- ------- ----- ------ -- - - ----- --------------- - ----- -- -- -------- ------------- --- ------ ------- ----------------------------------
总结
使用 redux-proptypes-pack 可以更轻松地使用 PropTypes 来捕获运行时错误,当您需要使用Redux属性时。该包还提供了一种创建PropTypes映射的简单方法。
建议您尝试使用此包来了解如何在 Redux 应用程序中使用 PropTypes。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6006700fe361a36e0bce8d52