gpt4 book ai didi

reactjs - (下一个/ react )从子组件中的按钮单击刷新 SWR - 我可以使用回调吗?? (功能到功能)

转载 作者:行者123 更新时间:2023-12-04 14:40:16 25 4
gpt4 key购买 nike

我正在使用 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)并且在过去几天还研究了钩子(Hook)并尝试了其他事情,但可以使用一些建议。

如果cart.js 是一个类组件,我会绑定(bind)我的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>
)
}

购物车.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>
)
}

最佳答案

您是否使用全局mutate (是的,有 2 个)?然后你需要向它传递一个 SWR key 。

全局mutate :

import useSWR, { mutate } from 'swr'

...

const { data } = useSWR(key, fetcher)
mutate(key) // this will trigger a refetch

或者使用绑定(bind) mutate ,并且您不需要通过 key :

import useSWR from 'swr'

...

const { data, mutate } = useSWR(key, fetcher)
mutate() // this will trigger a refetch

关于reactjs - (下一个/ react )从子组件中的按钮单击刷新 SWR - 我可以使用回调吗?? (功能到功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61653622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com