在react.js中为组件设置cookie [英] Set up cookie for the component in react.js

查看:102
本文介绍了在react.js中为组件设置cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读此文章如何我是否要在react代码中设置cookie?关于在reactjs代码中设置cookie,但是,我不能使用任何库,只能使用javascrip。
现在,我要实现的是在第一次访问时显示一个欢迎框。
我已经做过和测试过的是:1.欢迎框,它是jsx中的组件编码; 2. js中的cookie编码。这两个子部分都经过测试工作,但是,当我尝试将这两个部分组合成一个组件时,它就无法工作。

I have read this article How can I do to set cookie in the react code? about setting up cookie in reactjs code, however, I cannot use any library, what I can use is just the javascrip. Now, what I want to achieve is to show up a welcome box for the first time visit. What I have done and tested are: 1.the welcome box, it is a component coding in jsx; 2. the cookie coding in js. Both sub-part are tested working, however, when I tried to combine these two part into a single component, it is not working.

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'));

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

推荐答案

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

Alternatively to cookies you could use localStorage. Here's a basic example of that. It sets an item in the storage once the main component is mounted and reacts to that item in the render() method.

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>
  );
}

在JSFiddle上工作的演示<​​/ strong>

在其他组件中,您只需检查 localStorage.getItem('hasVisitedBefore')并根据该内容进行渲染。

In other components you could then just check for localStorage.getItem('hasVisitedBefore') and render things based on that.

这篇关于在react.js中为组件设置cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆