英文:
How to get cookies in getinitial props in nextjs?
问题
如何在getInitialprops中获取cookies以从Next.js页面中获取API?
英文:
How to get cookies in getInitialprops to fetch api from page in nextjs?
答案1
得分: 1
你可以从 npm 安装 Next Cookies。以下是链接:
https://www.npmjs.com/package/next-cookies
要读取所有的 cookies,你可以使用:
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;
英文:
You can install Next Cookies from npm. Here is link below
https://www.npmjs.com/package/next-cookies
To read all cookies you can use
const allCookies = cookies(ctx);
To read single cookies
const { myCookie } = cookies(ctx);
Example
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
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论