在React中调用函数并渲染子组成部分的最佳方法是什么?

发布于 2025-01-27 02:25:45 字数 2121 浏览 3 评论 0原文

我有以下代码,我想调用一个函数并渲染子组件。实现这一目标的最佳方法是什么?

import AddOrder from './AddOrder'

return (
<Button onClick={handleCheckout}>Checkout</Button>
)

const handleCheckout = () => {
        <AddOrder />
        fetch("http://localhost:5000/create-checkout-session", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                items: data?.getUser ? data.getUser.cart : cart,
                email: currentUser ? currentUser.email : undefined,
            }),
        })
            .then(async (res) => {
                if (res.ok) return res.json();
                const json = await res.json();
                return await Promise.reject(json);
            })
            .then(({ url }) => {
                window.location = url;
            })
            .catch((e) => {
                console.error(e.error);
            });
    };

我尝试制作一个名为handleall的新功能,然后添加这样的函数:

function handleAll(){
   handleCheckout()
   <AddOrder />
}

addorder.js:

function AddOrder() {
  const d = new Date();
  let text = d.toString();
  const { currentUser } = useContext(AuthContext);
  
  const { data, loading, error } = useQuery(queries.GET_USER_BY_ID, {
    fetchPolicy: "cache-and-network",
    variables: {
        id: currentUser.uid
    },
});
const [addOrder] = useMutation(queries.ADD_ORDER); 
useEffect(() => {
    console.log('hi')
})
if(error) {
    return <h1> error</h1>;
   }
   
if(loading) {
    return <h1> loading</h1>;
   }
if (data){
let newCart = []
for(let i=0; i< data.getUser.cart.length; i++){
    newCart.push({quantity: data.getUser.cart[i].quantity, _id: data.getUser.cart[i]._id})
}
console.log(newCart)
  addOrder({
    variables: {
        userId: currentUser.uid, status: 'ordered', createdAt: text, products: newCart
    }
  });
  console.log("hello")
}
}
export default AddOrder;

这也不起作用。当我重新加载它时,它将在MongoDB集合中添加3个相同顺序的副本。正确的方法是什么?

I have the below code, I want to call a function and render a child component onCLick. What is the best way to achieve this?

import AddOrder from './AddOrder'

return (
<Button onClick={handleCheckout}>Checkout</Button>
)

const handleCheckout = () => {
        <AddOrder />
        fetch("http://localhost:5000/create-checkout-session", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                items: data?.getUser ? data.getUser.cart : cart,
                email: currentUser ? currentUser.email : undefined,
            }),
        })
            .then(async (res) => {
                if (res.ok) return res.json();
                const json = await res.json();
                return await Promise.reject(json);
            })
            .then(({ url }) => {
                window.location = url;
            })
            .catch((e) => {
                console.error(e.error);
            });
    };

I tried making a new function called handleAll and adding it like this:

function handleAll(){
   handleCheckout()
   <AddOrder />
}

AddOrder.js:

function AddOrder() {
  const d = new Date();
  let text = d.toString();
  const { currentUser } = useContext(AuthContext);
  
  const { data, loading, error } = useQuery(queries.GET_USER_BY_ID, {
    fetchPolicy: "cache-and-network",
    variables: {
        id: currentUser.uid
    },
});
const [addOrder] = useMutation(queries.ADD_ORDER); 
useEffect(() => {
    console.log('hi')
})
if(error) {
    return <h1> error</h1>;
   }
   
if(loading) {
    return <h1> loading</h1>;
   }
if (data){
let newCart = []
for(let i=0; i< data.getUser.cart.length; i++){
    newCart.push({quantity: data.getUser.cart[i].quantity, _id: data.getUser.cart[i]._id})
}
console.log(newCart)
  addOrder({
    variables: {
        userId: currentUser.uid, status: 'ordered', createdAt: text, products: newCart
    }
  });
  console.log("hello")
}
}
export default AddOrder;

This did not work either. When I reload this it add 3 copies of the same order to the mongodb collection. What is the right way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文