【问题标题】:How do I get cookies in react js using react-cookie?如何使用 react-cookie 在 react js 中获取 cookie?
【发布时间】:2018-09-15 15:59:45
【问题描述】:

react-cookie 文档有这个例子

import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
  static propTypes = {
    cookies: instanceOf(Cookies).isRequired
  };

  componentWillMount() {
    const { cookies } = this.props;

    this.state = {
      name: cookies.get('name') || 'Ben'
    };
  }

  handleNameChange(name) {
    const { cookies } = this.props;

    cookies.set('name', name, { path: '/' });
    this.setState({ name });
  }

我可以在不使用 componentWillMount 的情况下使用 cookies.get 吗?

【问题讨论】:

    标签: reactjs cookies react-cookie


    【解决方案1】:

    那里有一点错过使用生命周期钩子。

    您应该在类构造函数中为state 赋予初始值。

    例如

    class Example extends React.Component {
      constructor(props){
        super(props)
        this.state = {
          name: this.props.cookies.get('name') || 'Ben',
        }
      }
    ...
    

    或者如果你只使用更新的 ES7 语法

    class Example extends React.Component {
        state = {
          name: this.props.cookies.get('name') || 'Ben',
        }
    ...
    

    constructor -下例不需要函数

    componentWillMount life-cycle 在即将发布的 React 版本中也将被弃用,因此我建议避免使用它。

    相应地替换它

    static getDerivedStateFromProps(nextProps, prevState){
       return {username: nextProps.username}
    }
    

    看看这里的区别,我们返回正常的Object,然后将它传递给组件状态。所以在这里username 将被传递给state

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-09
      • 2019-01-01
      • 2023-02-02
      • 2018-03-13
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多