根据存储的Cookie(selectedRetailerId
)中的特定值,源(API端点)不同。
我试图将cookie的值存储在名为retailer_id的变量中,并使用它来确保调用正确的端点。
这是我正在尝试的...
<OTHER CODE IS REDACTED>
ReactDOM.render(
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var retailer_id = getCookie(selectedRetailerId);
<DeliveryOptionsTable source="http://<REDACTED>/delivery_options/{retailer_id}" />,
document.getElementById('deliveryOptionsContainer')
)
但是这会返回一个Uncaught SyntaxError。可能是因为这段代码不应该在ReactDOM.render
中。
Uncaught SyntaxError: http://localhost:8000/src/app.js: Unexpected token (130:2)
128 | }
129 |
> 130 | var retailer_id = getCookie(selectedRetailerId);
| ^
131 |
132 | <DeliveryOptionsTable source="http://<REDACTED>/delivery_options/{retailer_id}" />,
133 | document.getElementById('deliveryOptionsContainer')
使用React执行此操作的正确方法是什么?
答案 0 :(得分:1)
试试这个:
// Defined somewhere outside ReactDOM.render (I'd recommend a helpers.js file)
// If you move it out of this file, be sure to import / require it
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
ReactDOM.render(
<DeliveryOptionsTable source={"http://<REDACTED>/delivery_options/" + getCookie(selectedRetailerId)} />,
document.getElementById('deliveryOptionsContainer')
)