在react.js中为组件设置cookie

时间:2017-06-04 10:44:44

标签: javascript reactjs cookies

我已经阅读了这篇文章How can I do to set cookie in the react code?关于在reactjs代码中设置cookie,但是,我不能使用任何库,我可以使用的只是javascrip。 现在,我想要实现的是第一次访问时出现一个欢迎盒。 我所做的和测试的是:1。欢迎盒,它是jsx编码的组件; 2.用js编码的cookie。两个子部分都经过测试工作,但是,当我尝试将这两个部分组合成一个组件时,它无法正常工作。



var Child = React.createClass({
  render: function() {
    return (
       <div className="container">
         <p>Welcome to our website</p>
         <button onClick={this.props.onClick}>Click me to close</button>
       </div>
    );
  }
});

var ShowHide = React.createClass({
createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
},

readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return "";
},

eraseCookie(name) {
	createCookie(name,"",-1);
},

firstVisit() {
  var isFirstVisit;
	var result = readCookie('firstVisit');
    if (result == "") {
        createCookie('firstVisit', 'true', 365);
        isFirstVisit = true;
		return isFirstVisit;
    }
    else {
		isFirstVisit = false;
		return isFirstVisit;
	}
},
  
getInitialState: function () {
    if(firstVisit()) {
      return { childVisible: true };
    }
    else 
    {
      return { childVisible: true };
    }
},

onClick: function() {
  this.setState({childVisible: !this.state.childVisible});
},
  
  render: function() {
    return(
      <div>
        {
          this.state.childVisible
            ? <Child onClick={this.onClick} />
            : null
        }
      </div>
    )
  },
});
 
React.render(<ShowHide />, document.getElementById('container'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以使用localStorage替代Cookie。这是一个基本的例子。一旦安装了主要组件,它就会在存储中设置一个项目,并在render()方法中对该项目做出反应。

componentDidMount() {
  // Get item from localStorage and save it to a constant.
  const hasVisitedBefore = localStorage.getItem('hasVisitedBefore');

  // Check if the user has visited the site (component) before.
  if (!hasVisitedBefore) {
    // If not, set the component state (or dispatch an action if you need)
    // Also set the localStorage so it's globally accessible.
    this.setState({ hasVisitedBefore: false });
    localStorage.setItem('hasVisitedBefore', true);
  }
}

// Based on the state set in `componentDidMount()`, show or hide the welcome modal.
render() {
  return (
    <div>
      {this.state.hasVisitedBefore
        ? 'Welcome back!'
        : 'Welcome for the first time!'}
    </div>
  );
}

Working demo on JSFiddle

在其他组件中,您可以检查localStorage.getItem('hasVisitedBefore')并根据它进行渲染。