2017-08-16 83 views
0

我在react/redux應用中使用react-cookie v2。要設置cookie,您需要將組件包裝在HOC withCookies(component)中,那麼您可以使用this.props.cookies.set('first_cookie', someCookie);來設置cookie。在util文件中使用react-cookie

但是,我想在我的所有組件都可以用來設置cookie的util文件中設置我的cookie。例如。

storageUtil.js 
export const setToCookies = (key, value, options) => { 
    cookies.set(key, value, options); 
}; 

此util的文件不能與withCookies,因此犯規直接有餅乾包裹。 我可以從使用組件(setToCookies(cookiesInstance, key, value, options))傳入cookie實例,但我寧願在某種程度上可能的情況下在util文件中導入cookie實例。

這必須是一個非常常見的用例(在util文件中處理cookie),我只是無法弄清楚這樣做的最佳方法。

回答

0

我會在搜索通用解決方案時寫出我發現的兩種方法。如果提供更好的解決方案,我會改變接受的答案。

解決方案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 
     ); 
    }; 
} 

用作:

  1. 進口和包裹export default withCustomCookies(Component);
  2. 使用這樣的內部組件this.props.getFromCookies(COOKIE_NAME);

解決方案2:

使用普通cookieUtils文件,並通過在餅乾:

cookieUtils.js 
export const setToCookies = (cookies, key, value, options) => { 
    // Stuff to always do when setting a cookie 
    cookies.setCookie(key, value, options); 
}; 

用途爲:在你的組件

  1. 導入setToCookies和所使用的組件withCookies(withCookies(NameOfComponent)) 。
  2. 使用組件中的方法爲setToCookies(this.props.cookies, key, value, options);
相關問題