javascript 如何在React中将变量的值从一个组件传递到另一个组件

dsf9zpds  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(131)

我使用两个组件:-"CartContainer.jsx”用于计算用户添加到购物车中的产品的成本。

更新日期:

import React, { useEffect, useState } from "react";
import { useStateValue } from "../context/StateProvider";
import { actionType } from "../context/reducer";
//another imports
import { Link } from "react-router-dom";
import PaymentContainer from "./PaymentContainer";

const CartContainer = () => {
    const [{ cartShow, cartItems, user }, dispatch] = useStateValue();
    const [flag, setFlag] = useState(1);
    const [tot, setTot] = useState(0);

    //another methods

    useEffect(() => {
        let totalPrice = cartItems.reduce(function (accumulator, item) {
            return accumulator + item.qty * item.price;
        }, 0);
        setTot(totalPrice);
        console.log(tot);
    }, [tot, flag]);

    //another methods

    return (
        <motion.div initial... animate... exit... class...">

        //something code

            {/* bottom section */}

        //something code

                    {/* cart total section code */}
                    <div class...>
                        <div class...>
                            <p class...>Sub Total</p>
                            <p class...>$ {tot}</p>
                        </div>
                        <div class...>
                            <p class...>Delivery</p>
                            <p class...>$ 2.5</p>
                        </div>

                        //another code

                        <div class...>
                            <p class...>Total</p>
                            <p class...>${tot + 2.5}</p>
                        </div>

                        {user ? (
                            <Link to={'/payment'}> *//it's link to PaymentContainer*
                                <motion.button whileTap={{ scale: 0.8 }} type="button" class...>Check Out</motion.button>
                            </Link>
                        ) : (
                            //another code
                        )}
                    </div>
                    <div>
                        <PaymentContainer totalAmount={tot} />
                    </div>
                </div>
            ) : (
        //another code
            )}
        </motion.div>
    );
};

export default CartContainer;

-"PaymentContainer.jsx”此组件与Stripe.js一起工作,并具有“amount”变量。

更新日期:

import React from "react";

const PaymentContainer = ({totalAmount}) => {
  const containerAmount = totalAmount;
  console.log(totalAmount);
  return (
    <div>
      <h2>Total: {containerAmount}</h2>
    </div>
  );
};

export default PaymentContainer;

我想从“CartContainer.jsx”项目的总成本被分配到“amount”变量在“PaymentContainer.jsx”谢谢大家:)
我发现一个类似的问题在这个论坛,并试图应用解决方案,但我不能。我试图适应这个代码在文件“PaymentContainer.jsx”

const handleInputChange = (e) => {   
  const valueFilterActive = document.getElementById("activeFilter").value;
  const valueFilterName = document.getElementById("bussFilter").value;
  // this will set `inputValues` variable to be an object with `valueFilterActive` and `valueFilterName` properties
  setInputValues({valueFilterActive, valueFilterName})
  alert(valueFilterName+valueFilterActive);   
};

**更新日期:**App.js

import React, { useEffect } from "react";
import { Route, Routes } from "react-router-dom";
import { AnimatePresence } from "framer-motion";
import { CreateContainer, Header, MainContainer, PaymentContainer } from "./components";
import { useStateValue } from "./context/StateProvider";
import { getAllFoodItems } from "./utils/firebaseFunctions";
import { actionType } from "./context/reducer";

const App = () => {
    const [{foodItems}, dispatch] = useStateValue();

    const fetchData = async () => {
        await getAllFoodItems().then(data => {
            dispatch({
                type : actionType.SET_FOOD_ITEMS,
                foodItems : data,
            });
        });
    };

    useEffect(() => {
        fetchData();
    }, []);

    return (
        <AnimatePresence mode="wait">
            <div class...>
                <Header />

                <main class...>
                    <Routes>
                        <Route path="/*" element={<MainContainer />} />
                        <Route path="/createItem" element={<CreateContainer />} />

            //here PaymentContainer
                        <Route path="/payment" element={<PaymentContainer />} /> here PaymentContainer
            //here PaymentContainer

                    </Routes>
                </main>
            </div>
        </AnimatePresence>
    );
}

export default App

更新日期:

当我将产品添加到购物车并获得金额时,浏览器控制台,但当我通过“链接”转到“付款容器”时,该值未定义。

h7appiyu

h7appiyu1#

在React中,可以通过属性或全局状态将数据传递给其他组件,因此一种方法是在CartContainer.jsx中呈现PaymentContainer.jsx并将数据传递给它。
例如:

import React, { useEffect, useState } from "react";
// your other imports
import PaymentContainer from "./PaymentContainer";

const CartContainer = () => {
    const [tot, setTot] = useState(0);
    // your previous data

return (
  // your previous stuff
  <PaymentContainer totalAmount={tot} />
 )
}

export default CartContainer

您的支付容器也需要接收 prop 查看

const PaymentContainer = ({totalAmount}) => {
  console.log(totalAmount)
  // your previous stuff
  return (
    // your previous stuff
  )
}

参考:https://reactjs.org/docs/components-and-props.html

yiytaume

yiytaume2#

问题

您正在 * 至少 * 两个位置渲染PaymentContainer组件,一个是在CartContainer中,其中传递了totalAmount属性:

<div>
  <PaymentContainer totalAmount={tot} />
</div>

在没有 prop 通过的路线上:

<Route path="/payment" element={<PaymentContainer />} />

当通过CartContainer中的Link导航到第二个时,总计未定义。

A溶液

不清楚为什么要在两个地方 * 以不同的方式 * 呈现PaymentContainer,所以我将忽略这一部分。如果要在路由上呈现PaymentContainer并向其传递数据,则将通过链接以路由状态传递它。
tot状态实际上也是不必要的,因为它是从 * 实际 * cartItems状态 * 派生 * 的“状态”。它通常被认为是一个将派生状态存储在React状态中的React反模式。您应该在每个渲染周期本地计算和使用它。
请注意,在几乎100%的用例中,您发现自己在编写useState/useEffect钩子组合时,真正应该使用的是useMemo钩子来计算***和记忆***一个稳定的值引用。
示例:
一个二个一个一个
代码示例:

const CartContainer = () => {
  const [{ cartShow, cartItems, user }, dispatch] = useStateValue();
  const [flag, setFlag] = useState(1);

  // another methods

  const totalAmount = React.useMemo(() => {
    return cartItems.reduce(function (accumulator, item) {
      return accumulator + item.qty * item.price;
    }, 0);
  }, [cartItems]);

  // another methods

  return (
    <motion.div initial... animate... exit... class...">
      ...

      {user ? (
        <Link to="/payment" state={{ totalAmount }}> // <-- pass totalAmount in state
          <motion.button
            whileTap={{ scale: 0.8 }}
            type="button"
            class...
          >
            Check Out
          </motion.button>
        </Link>
      ) : (
        //another code
      )}

      ...
      <PaymentContainer totalAmount={totalAmount} />
      ...
    </motion.div>
  );
};
import React from "react";
import { useLocation } from 'react-router-dom';

const PaymentContainer = ({ totalAmount }) => {
  const { state } = useLocation();

  const containerAmount = state.totalAmount || totalAmount || 0;

  React.useEffect(() => {
    console.log(totalAmount);
  }, [totalAmount]);

  return (
    <div>
      <h2>Total: {containerAmount}</h2>
    </div>
  );
};

相关问题