【问题标题】:Set a cookie in react to true all the time始终设置一个 cookie 以响应 true
【发布时间】:2021-07-27 11:47:26
【问题描述】:

我想将 cookie 设置为始终为真,而不是在发生某事或单击某事时。

因此有一些关于此的教程和文章。就我而言,它应该类似于:'mySpecialCookie = true'。

安装包:npm install react-cookie

是否需要在 index.js 和 App.js 中都导入?

我的 index.js 看起来像这样:

import React from 'react';
import ReactDOM from 'react-dom';
import configureStore from './store/configureStore';
import getMiddlewares from './middlewares';
import App from './containers/App';
import * as serviceWorker from './serviceWorker';

const storeConfig = configureStore(getMiddlewares());

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

serviceWorker.unregister();

所以我假设在 ReactDOM 内部应该改成这个?

import { CookiesProvider } from "react-cookie";
...
ReactDOM.render(
  <storeConfig.Provider store={storeConfig.store}>
    <CookiesProvider>
      <App />
    </CookiesProvider>
  </storeConfig.Provider>,
  document.getElementById('root')
);

在 App.js 中我使用 useCookies 钩子添加了它,但不知道在哪里使用它:

import React, { useEffect } from 'react';
import { useCookies } from 'react-cookie'; //// <---   added it here 
import { IntlProvider } from 'react-intl';
import { useSelector, shallowEqual, useDispatch } from 'react-redux';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import Main from './Main';
import OrderDetails from './OrderDetails';
import { fetchDictionary } from '../actions/dictionary';
import { getLanguageCode } from '../utils';
import { HOME_PAGE, ORDER_DETAILS } from '../constants/routes';

const App = () => {
  const dictionary = useSelector((state) => state.dictionary, shallowEqual);
  const routes = [
    { path: HOME_PAGE, component: Main },
    { path: `${ORDER_DETAILS}/:id`, component: OrderDetails }
  ];
  const dispatch = useDispatch();

  const [mySpecialCookie, setMySpecialCookie] = useCookies(true);  //// <---   added it here 

  useEffect(() => {
    dispatch(fetchDictionary(getLanguageCode()));
  }, [dispatch]);

  return (
    <IntlProvider
      key={dictionary.locale}
      locale={dictionary.locale}
      messages={dictionary.messages}>
      <Router>
        {routes.map((route, index) => (
          <Route
            key={index}
            path={route.path}
            exact
            component={route.component}
          />
        ))}
      </Router>
    </IntlProvider>
  );
};

export default App;

有什么建议吗?

【问题讨论】:

    标签: javascript reactjs cookies react-hooks react-cookie


    【解决方案1】:

    我找到了一种更短的方法来使用js-cookie

    在 App.js 文件中:

    ...
    import Cookies from 'js-cookie';
    ...
    
    const App = () => {
       ...
       Cookies.set('mySpecialCookie', true);
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 2011-03-21
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2014-01-12
      相关资源
      最近更新 更多