此文本已使用 Salesforce 机器翻译系统进行翻译。如需了解更多详情,请点击此处。
在本教程中,您将学习如何使用服务器端 Cookie 进行个性化设置。例如,您可以根据购物者是新购物者还是回头客显示不同的内容,例如向新购物者提供欢迎优惠横幅,向回头客提供促销优惠横幅。
建议在非生产环境中测试这些步骤,然后再将更改部署到生产环境。
在运行本教程中的命令之前,请将所有占位符替换为实际值。占位符的格式如 $PLACEHOLDER。
要完成本教程,请执行以下操作:
使用 PWA Kit 版本 3.1.0 或更高版本。
在本地计算机上,通过完成以下任一步骤来启用服务器端 Cookie:
设置环境变量 MRT_ALLOW_COOKIES=true。
或
传递 localAllowCookies 给 ssr.js 中的选项 runtime.CreateHandler。
对于所选环境,请使用 Managed Runtime (MRT) API 或 Runtime Admin 启用服务器端 Cookie:
allow_cookies 设置为 true。在 app/pages/home/index.jsx 中,为新购物者和回头客创建您选择的内容。或者创建适用于不同类别购物者的其他内容。
app/pages/home/index.jsx 的主页文件中:1import React, { useState, useEffect } from 'react';
2import Cookies from 'js-cookie'
3
4const Home = () => {
5 const [isNewShopper, setIsNewShopper] = useState();
6
7 useEffect(() => {
8
9 // Find out if the site visitor is a new shopper by checking for the isNewShopper cookie.
10 const isNewShopperCookie = Cookies.get('isNewShopper');
11
12 // If the cookie isn't found, set it on the server and treat the site visitor as a new shopper.
13 setIsNewShopper(isNewShopperCookie != null ? isNewShopperCookie === 'true' : true);
14 }, []);
15
16 return (
17 {isNewShopper ? (
18
19 // Show this message to a new shopper.
20 <h1>Welcome! We're glad you're here.</h1>
21 ) : (
22
23 // Show this message to a returning shopper.
24 <h1>Welcome back!</h1>
25 )}
26
27 // ... Code for the rest of your homepage
28 )
29}isNewShopper,较长的有效期是合适的。例如,一年。本节针对使用服务器端 Cookie 时可能遇到的常见错误提供建议的解决方案。
部署涉及服务器端 Cookie 的代码后,您没有得到预期的站点行为。
**原因:**您没有启用服务器端 Cookie。
**建议的解决方案:**启用服务器端 Cookie,如前提条件中所述。
用户会话或偏好中断。
**原因:**Cookie 过期或过早删除。
建议的解决方案:
有时,Cookie 在您网站的不同页面或组件中的行为不同,从而导致购物者体验不一致。
**原因:**与 Cookie 相关的逻辑不一致或分散。
建议的解决方案: