【问题标题】:Component is not getting updated value from Context组件未从 Context 获取更新的值
【发布时间】:2021-05-01 07:21:13
【问题描述】:

在 Home 组件中,我从 Product 上下文中获取产品详细信息。但是当上下文值发生变化时,更新的值不会出现在 Home 组件中。

这是家庭组件:

import React, { useEffect, useState } from "react";
import { useProductList } from "../../context/ProductContext/ProductContext";
import { WishListButton } from "../WishListButton/WishListButton";
import { Filters } from "../Filters/Filters";

const Home = () => {
  const { productList } = useProductList();
  /*let [gameList, setGameList] = useState();

  useState(() => {
    console.log(productList ? productList[0] : null);
    setGameList(productList);
  }, [productList]);*/

  console.log(productList);
  return (
    <div>
      <h1>Home</h1>
      <Filters />
      <div className="products">
        {productList
          ? productList.map((item, i) => (
              <div key={i} className="card">
                <div className="card-name">{item.name}</div>
                <div>
                  <WishListButton id={item._id} />
                </div>
                <div>Rs.{item.price}</div>
              </div>
            ))
          : null}
      </div>
    </div>
  );
};

export { Home };

这是我的 ProductContext

import { createContext, useContext } from "react";

export const ProductContext = createContext();

export function useProductList() {
  return useContext(ProductContext);
}

【问题讨论】:

    标签: reactjs use-context


    【解决方案1】:
    const {productList}= useContext(useProductList);
    

    你需要使用useContext钩子来获取值

    【讨论】:

    • 这就是我在产品上下文中所做的。刚刚更新了描述。
    【解决方案2】:

    发现问题。我之前就是这样做的

    const ascPriceState = state.sort((a, b) => (a.price > b.price ? 1 : -1));
    

    现在做这个

    state.sort((a, b) => (a.price > b.price ? 1 : -1));
    const ascPriceState = [...state];
    

    需要返回新对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 2017-04-23
      • 2019-12-25
      • 2020-01-03
      相关资源
      最近更新 更多