此文已使用 Salesforce 機器翻譯系統翻譯。更多詳細資料請參見此處。
在本教學中,您將學習如何使用伺服器端 Cookie 進行個人化設定。例如,您可以根據購物者是新購物者還是回頭客顯示不同的內容,像是向新購物者顯示歡迎優惠橫幅,向回頭客顯示促銷優惠橫幅。
建議在非 Production 環境中測試這些步驟,然後再將變更部署到生產 Production 環境。
在執行本教學的命令之前,請以實際值取代預留位置。預留位置的格式為:$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 相關的邏輯不一致或分散。
建議的解決方案: