我在我的app /redux应用程序中使用了app cookie v2。要设置cookie,需要将组件包装在一个特殊的withCookies(component)中,然后可以使用this.props.cookies.set('first_cookie', someCookie);设置cookie。
但是,我想在util文件中设置我的cookie,所有组件都可以使用这个文件来设置cookie。例如。
storageUtil.js
export const setToCookies = (key, value, options) => {
cookies.set(key, value, options);
};这个util文件不能用withCookies包装,因此不能直接使用cookie。我可以从using (setToCookies(cookiesInstance, key, value, options))传入cookie实例,但如果可能的话,我宁愿在util文件中导入cookie实例。
这必须是一个非常常见的用法(在util文件中处理cookie),我只是想不出最好的方法。
发布于 2017-08-16 14:42:39
在搜索通用解决方案时,我将编写找到起作用的两个方法。如果提供更好的解决方案,我将更改接受的答案。
解决方案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);
};用作:
withCookies(NameOfComponent))。setToCookies(this.props.cookies, key, value, options);https://stackoverflow.com/questions/45708003
复制相似问题