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吗?
发布于 2018-04-06 02:28:49
这里有一点生命周期钩子的使用上的疏漏。
您应该在类构造函数上为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 -function
在即将发布的React版本中,componentWillMount生命周期也将被弃用,因此我建议避免使用它。
对它的替换是相应的
static getDerivedStateFromProps(nextProps, prevState){
return {username: nextProps.username}
}看这里的不同之处,我们返回正常的Object,然后get传递给组件状态。所以在这里,username将被传递给state。
https://stackoverflow.com/questions/49678976
复制相似问题