gpt4 book ai didi

reactjs - 如何使用react-cookie在react js中获取cookie?

转载 作者:行者123 更新时间:2023-12-03 14:07:51 26 4
gpt4 key购买 nike

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 吗?

最佳答案

那里有一点没有使用生命周期钩子(Hook)。

您应该为类构造函数上的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',
}
...

构造函数 - 下面的示例不需要函数

componentWillMount 生命周期也将在即将发布的 React 版本中被弃用,因此我建议避免使用它。

相应地更换

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

看看这里的区别,我们返回正常的Object,然后将其传递到组件状态。因此,在这里用户名将被传递给状态

关于reactjs - 如何使用react-cookie在react js中获取cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49678976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com