[英]Using react-cookie in a util file
我在我的react / redux应用程序中使用react-cookie v2。 要设置cookie,您需要将组件包装在HOC withCookies(component)
,然后可以使用this.props.cookies.set('first_cookie', someCookie);
设置一个cookie。
但是,我想在所有文件都可以用来设置cookie的util文件中设置cookie。 例如。
storageUtil.js
export const setToCookies = (key, value, options) => {
cookies.set(key, value, options);
};
该withCookies
程序文件不能与withCookies
一起包装,因此不直接包含Cookie。 我可以从using组件( setToCookies(cookiesInstance, key, value, options)
)中传入cookie实例,但是我宁愿以某种方式在实用程序文件中导入cookie实例。
这必须是一个非常普通的用例(以处理util文件中的cookie),我只是不知道执行此操作的最佳方法。
我将编写在寻找通用解决方案时发现可以使用的两种方法。 如果提供更好的解决方案,我将更改接受的答案。
解决方案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);
导入和包装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);
};
用于:
withCookies(NameOfComponent)
)上使用withCookies。 setToCookies(this.props.cookies, key, value, options);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.