【问题标题】:How to get cookies in getinitial props in nextjs?如何在 nextjs 的 getinitialprops 中获取 cookie?
【发布时间】:2020-01-06 20:58:41
【问题描述】:

如何在getInitialprops 中获取cookie 以从nextjs 中的页面获取api?

【问题讨论】:

  • 您能否分享您的代码以尝试执行您需要的操作,以便提供更多上下文?

标签: reactjs next.js


【解决方案1】:

您可以从 npm 安装 Next Cookies。下面是链接

https://www.npmjs.com/package/next-cookies

要读取您可以使用的所有 cookie

const allCookies = cookies(ctx);

读取单个 cookie

const { myCookie } = cookies(ctx);

例子

import React from 'react'
import cookies from 'next-cookies'

class NameForm extends React.Component {
  static async getInitialProps(ctx) {
    return {
      initialName: cookies(ctx).name || ''
    }
  }

  constructor(props) {
    super(props);
    this.state = {name: props.initialName || ''};
    this.handleChange = this.handleChange.bind(this);
    this.reset = this.reset.bind(this);
  }

  handleChange(event) {
    const newName = event.target.value;
    this.setState({name: newName});
    document.cookie = `name=${newName}; path=/`;
  }

  reset() {
    this.setState({name: ''});
    document.cookie = 'name=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT';
  }

  render() {
    return (
      <div>
        <p>Hi {this.state.name}</p>
        <p>Change cookie: <input
            type="text"
            placeholder="Your name here"
            value={this.state.name}
            onChange={this.handleChange}
          />!
        </p>
        <p>Delete cookie: <button onClick={this.reset}>Reset</button></p>
      </div>
    );
  }
}

export default NameForm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 2017-11-29
    • 2020-04-08
    • 1970-01-01
    • 2018-05-05
    • 2019-01-01
    • 1970-01-01
    • 2020-07-13
    相关资源
    最近更新 更多