我哪里做错了?我正在尝试使用来自API响应的数据。我想要我的React应用程序打开一个新的窗口,页面,或任何其他比同一页面。然后显示从这个API获取的数据。如果您使用示例来帮助初级开发人员学习,这是最好的。我们都知道技术术语比编写实际代码更难。
如果你想在POSTMAN中测试API:
标记:fb83b937 - 2739 - 3 - d6e - 9519 - 09387 - b92dfaeAPI: https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/checkout/
请在正文中使用:
{
"transactionReference": "string",
"paymentMethod": "CreditCard",
"checkoutOrderUrl": "http://www.test.com/",
"user": {
"name": "string",
"msisdn": "+27610983142",
"email": "test@test.com" },
"payementMethodDetail": {
"RedirectUrl": "http://www.test.com",
"PurchaseEventWebhookUrl": "http://www.test.com" },
"bundle": [
{
"ProductCode": "317",
"Amount": 5000,
"CurrencyCode": "ZAR",
"Quantity": 1 }
]
}
这是我目前的解决方案:我正在做POST请求时,用户单击现在支付。只有当用户这样做时,我才需要显示加载消息并在新窗口/页面/路径中显示结果。
const handleSubmit = async () => {
const token = "fb83b937-2739-3d6e-9519-09387b92dfae";
const data = {
transactionReference: "string",
paymentMethod: "CreditCard",
checkoutOrderUrl: "http://www.test.com/",
user: {
name: name,
msisdn: phone,
email: email,
},
payementMethodDetail: {
RedirectUrl: "http://www.test.com",
PurchaseEventWebhookUrl: "http://www.test.com",
},
bundle: cart.map((item) => ({
ProductCode: `${item.ProductCode}`,
Amount: item.amount,
CurrencyCode: item.currencyCode,
Quantity: item.quantity,
})),
};
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(data),
};
await fetch(
"https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/checkout/",
requestOptions
)
.then((response) => response.json(),
console.log("Data Sent")
)
.then((res) => {
Navigate(<Payment/>, {state: res})
});
};
感谢那些将要帮助我的人。
Issue
从我对你的问题的理解来看,你想要导航到一个用指定的响应有效负载呈现Payment
组件的路由。问题是,您不能像这样从回调函数返回Navigate
组件,并期望它对UI中的任何更改产生影响。Navigate
组件要么需要作为组件结果的一部分呈现,要么需要作为命令式导航操作呈现。
解决方案导入并使用useNavigate
钩子访问navigate
函数,发出一个命令式导航,POST响应数据在route状态
的例子:
import { useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
...
const handleSubmit = async () => {
...
await fetch(
"https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/checkout/",
requestOptions
)
.then((response) => response.json())
.then((payment) => {
navigate("/confirmation", { state: { payment } });
});
};
创建渲染Payment
组件的路由:
<Routes>
... other routes ...
<Route path="/confirmation" element={<Payment />} />
...
</Routes>
在Payment
组件中,使用useLocation
钩子访问传递的路由状态。
import { useLocation } from 'react-router-dom';
...
const Payment = () => {
const { state } = useLocation();
const { payment } = state || {};
...
};
标题>