在寻找通用解决方案时,我将编写我发现的两种方法。如果提供更好的解决方案,我将更改接受的答案。
解决方案1:
withCustomCookies.js
import React from 'react';
import { withCookies } from 'react-cookie';
export function withCustomCookies(Component) {
return (props) => {
// CookieComponent needs a capital letter bc of JSX
let ExtendedCookieComponent = withCookies(withEncapsulatedCookies(Component));
return (
<ExtendedCookieComponent
{...props} />
);
};
}
export function withEncapsulatedCookies(Component) {
return (props) => {
// Only expose our own cookies methods defined in this scope
const {
// Dont expose cookies in using component
cookies, // eslint-disable-line no-unused-vars
...cleanedProps
} = props;
function getFromCookies(key) {
// Stuff to always do when getting a cookie
return cookies.get(key);
}
function setToCookies(key, value, options) {
// Stuff to always do when setting a cookie
cookies.set(key, value, options);
}
return (
<Component
getFromCookies={getFromCookies}
setToCookies={setToCookies}
{...cleanedProps} /> // All Props except for cookies
);
};
}
用作:
- 导入和包装
export default withCustomCookies(Component);
- 在组件内部这样使用
this.props.getFromCookies(COOKIE_NAME);
解决方案2:
使用常规的 cookieUtils 文件并传入 cookie:
cookieUtils.js
export const setToCookies = (cookies, key, value, options) => {
// Stuff to always do when setting a cookie
cookies.setCookie(key, value, options);
};
用于:
- 在您的组件中导入 setToCookies 并在您的组件 (
withCookies(NameOfComponent)
) 上使用 withCookies。
- 使用组件中的方法作为
setToCookies(this.props.cookies, key, value, options);