Dan*_*och 2 callback reactjs next.js
我正在使用 Next.js 制作购物车组件,并且在更新购物车数据后出现刷新问题。我的购物车组件是 Next.js 文档(https://nextjs.org/docs/basic-features/data-fetching#fetching-data-on-the-client-side)中推荐的功能,我在里面有一个组件这称为 products.js,包含我的产品列表,每个产品都有 +/- 按钮来调整它们的数量(发布到数据库)。
我的数据库更新了,但我需要重新获取购物车组件上的数据客户端。我意识到我可以使用 swrs 'mutate' 重新获取 swr 调用,但是当我尝试将回调函数从我的 cart.js 传递到 products.js 时,它显示在控制台日志中,但没有在我的按钮单击。
cartUpdate = cartUpdate.bind(this)在过去的几天里,我尝试过并研究过钩子并尝试了其他事情,但可以使用一些建议。
如果cart.js 是一个类组件,我会cartUpdate在将它传递给product.js 之前绑定我的函数,这会起作用,但是当它是函数对函数还是类对函数时,我似乎无法做同样的事情。
我已经在这几天了,我不确定我是否试图违反一些我不知道的规则,或者我如何重新获取我的数据,同时仍然保持我的代码分离和有点干净.
产品.js:
export default function productsection ({products, cart, cartproducts, feUpdate}){
console.log("feUpdate", feUpdate)
return (
<div>
{products.map((product, i) => (
<div className="flex-column justify-content-center mx-2">
<div className="mx-auto card w-100 p-2 my-2">
<div className="card-body ">
<h5 className="card-title text-center">{product.name}</h5>
<div className="d-flex justify-content-between">
{/* <p>Size Selected: {product.size}</p> */}
{/* <p>Total: {product.price * props.cartproducts[i].qty} USD</p> */}
<button className='btn btn-light mx-2' onClick={() => {
fetch(`/api/db/editCartProducts`,{
method: 'post',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({task: 'ADD', orderid: cart.orderid, productid: product.productid})
}).then(res => {console.log("adding: " + product.name + " from cart.", "id: " + product.productid); () => feUpdate(); console.log("passed update")})
}}
>
Add
</button>
<p className="px-2">Price: {product.price} USD EA</p>
<p className="px-2">{product.description}</p>
<p>Quantity: {cartproducts[i].qty}</p>
<button className='btn btn-light mx-2' onClick={() => {
fetch(`/api/db/editCartProducts`,{
method: 'post',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({task: 'REMOVE', orderid: cart.orderid, productid: product.productid})
}).then(res => {console.log("removing: " + product.name + " from cart.", "id: " + product.productid);() => feUpdate(); console.log("passed update")})
}}>
Remove
</button>
</div>
</div>
</div>
</div>
))}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
购物车.js:(主要观点是cartUpdate()&ProductSection我正在传递cartUpdate)
function Cart (props){
const fetcher = (...args) => fetch(args[0], {
method: 'post',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({[args[2]]:args[1]})
}).then(res => res.json())
let User = Cookies.get('User')
async function cartUpdate(){
console.log("mutate called");
console.log("isValidated: ", isValidating)
mutate();
console.log(cartitems);
console.log("isValidated: ", isValidating)
}
const { data: user, error} = useSWR(() => [url1, User, "User"], fetcher, {suspense: false });
console.log("User returned: ", user)
const { data: cart, error2} = useSWR(() => [url2, user.customerid, 'User'], fetcher, { suspense: false });
console.log("Cart returned: ", cart)
// const OrderId = Cookies.get('orderid')
const { data: cartitems, error3, mutate, isValidating} = useSWR(() => [url3, cart.orderid, 'orderid'], fetcher, { suspense: false });
console.log("Cart items: ", cartitems)
console.log("before productdetails call")
const { data: productdetails, error4} = useSWR(() => [url4, cartitems, 'productids'], fetcher, { suspense: false });
console.log("productdetails: ", productdetails)
let itemtotal = 0;
let costtotal = 0;
if(productdetails && cartitems){
productdetails.forEach((product, i) => {
itemtotal = itemtotal + (cartitems[i].qty);
costtotal = costtotal + (product.price * cartitems[i].qty)
})
console.log("totals: ", itemtotal, costtotal)
}
if (productdetails) {
console.log(props)
// foreach to get total price of cart and total items count.
return (
<div className="jumbotron jumbotron-fluid mt-5 d-flex flex-column justify-content-center">
<Header name={user.fname}/>
<div className={!isValidating? "card text-center" : "text-center"}>isValidating??</div>
<div className="d-flex flex-row justify-content-center">
<button onClick={() => feUpdate()}>Big Update Button</button>
<ProductSection feUpdate={cartUpdate} products={productdetails} cart={cart} cartproducts={cartitems} />
<Summery itemtotal={itemtotal} costtotal={costtotal}/>
</div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
您是否在使用全局mutate(是的,有 2 个)?然后你需要向它传递一个 SWR 密钥。
全球mutate:
import useSWR, { mutate } from 'swr'
...
const { data } = useSWR(key, fetcher)
mutate(key) // this will trigger a refetch
Run Code Online (Sandbox Code Playgroud)
或者使用 bound mutate,你不需要传递key:
import useSWR from 'swr'
...
const { data, mutate } = useSWR(key, fetcher)
mutate() // this will trigger a refetch
Run Code Online (Sandbox Code Playgroud)
因此,为了结束这个问题,我在处理了项目的其他区域后又回到了它,并意识到它就像使用普通函数调用而不是箭头函数一样简单,例如.then(res => {feUpdate()})不知道我是如何忽略了这一点或发生了什么之前进行过测试,但现在可以正常工作了。我想休息一下,然后带着新的眼光回来就可以了。
| 归档时间: |
|
| 查看次数: |
4280 次 |
| 最近记录: |