【问题标题】:Set up cookie for the component in react.js在 react.js 中为组件设置 cookie
【发布时间】:2017-11-05 07:08:12
【问题描述】:

我已经阅读了这篇关于在 reactjs 代码中设置 cookie 的文章How can I do to set cookie in the react code?,但是,我不能使用任何库,我可以使用的只是 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'));
<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>

【问题讨论】:

  • 您绝对有必要使用cookies吗?改用localStorage 可能更容易。
  • 如果那样的话,能否给我一些指导或相关文章,谢谢。

标签: javascript reactjs cookies


【解决方案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') 并根据它进行渲染。

【讨论】:

  • 非常感谢您的帮助,现在,我已经完成了我需要做的事情。
猜你喜欢
  • 1970-01-01
  • 2021-08-27
  • 2017-11-04
  • 1970-01-01
  • 2020-10-06
  • 2015-04-13
  • 2021-12-15
  • 1970-01-01
  • 2020-03-13
相关资源
最近更新 更多