cookie值未定义(react-cookie 2.0.6)

时间:2017-05-10 12:17:44

标签: javascript reactjs cookies react-redux

我在实施react cookies v ^ 2时遇到问题。我使用webpack-dev-server进行测试 这是一个令人满意的日志:

警告:上下文类型失败:上下文cookieswithCookies(App)标记为必需,但其值为undefined
          in withCookies(App)
          在提供者

/App.jsx:

import React, { Component } from 'react';
import { CookiesProvider, withCookies, Cookies} from 'react-cookie'
import {Route, Switch, BrowserRouter} from 'react-router-dom';

//import RequireAuth from './RequireAuth';
import NotFoundPage from './NotFoundPage';
import LandingPage from './LandindPage';
import WorkSpace from './WorkSpace';
import ActivationPage from './ActivationPage';

class App extends Component {
  render() {
    return (
      <CookiesProvider>
        <BrowserRouter>
          <Switch>
            <Route exact={true} path="/" component={LandingPage}/>
            <Route path="/workspace" component={WorkSpace}/>
            <Route exact path="/activation" component={ActivationPage}/>
            <Route path="*" component={NotFoundPage}/>
          </Switch>
        </BrowserRouter>
      </CookiesProvider>
    );
  }
}

export default withCookies(App);

/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';
import reducers from './reducers';
import { Provider } from 'react-redux';

import App from './components/App';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);

ReactDOM.render(
  <Provider store = {store}>
    <App/>
  </Provider>
  ,
  document.getElementById('root'));

2 个答案:

答案 0 :(得分:3)

以前react-cookie npm包中的功能似乎已移至universal-cookieuniversal-cookie repository现在的相关示例是:

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman

Source(原始答案作者的所有作品)

答案 1 :(得分:1)

HttpOnly

如果您确信自己正确使用了universal-cookie(或类似的软件包),但仍然得到undefined
(在源代码中)检查Cookie的设置方式(或使用Cookie检查器浏览器扩展程序(例如EditThisCookie for Chrome进行检查,并检查HttpOnly属性)。< br /> 如果将HttpOnly设置为true,那么(根据定义)没有JavaScript将能够访问它(即HttpOnly的{​​{3}})。因此,该值将返回为undefined

来自the point

限制访问cookie

JavaScript HttpOnly API无法访问具有Document.cookie属性的cookie;它仅发送到服务器。例如,持久化服务器端会话的cookie不需要对JavaScript可用,而应具有HttpOnly属性。此预防措施有助于缓解跨站点脚本(developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)攻击。