【问题标题】:Why can't i fetch data from a passed value?为什么我不能从传递的值中获取数据?
【发布时间】:2021-11-09 05:10:57
【问题描述】:

我试图通过将值从我的 context.js 传递到我的 ProductsList.js 来获取我的产品信息值。但是,当我 console.log ProductsList.js 中的值时,我的控制台没有获取数据......我不知道出了什么问题,有人可以帮助我吗?非常感谢!

这是我的 context.js:

import React from "react";
import {
    storeProducts,
    detailProduct
} from "./data";

const ProductContext = React.createContext();

//provider
//consumer

class ProductProvider extends React.Component {
    state = {
        products: storeProducts,
        detailProduct: detailProduct
    };
    handleDetail = () => {
        console.log("hello products");
    };
    addToCart = () => {
        console.log("hello details");
    };
    render() {
        return ( <
            ProductContext.Provider value = {
                {
                    ...this.state,
                        handleDetail: this.handleDetail,
                        addToCart: this.addToCart
                }
            } >
            <
            /ProductContext.Provider>
        );
    }
}

const ProductConsumer = ProductContext.Consumer;

export {
    ProductProvider,
    ProductConsumer
};

这是我的 ProductsList.js:

import React, { Component } from "react";
import Product from "./Product";
import Title from "./Title.js";
import { storeProducts } from "../data";

import { ProductConsumer } from "../context";
export default class ProductsList extends Component {
  state = {
    products: storeProducts,
  };
  render() {
    return (
      <React.Fragment>
        <div className="py-5">
          <div className="container">
            <Title name="our" title="products" />
            <div className="row">
              <ProductConsumer>
                {" "}
                {(value) => {
                  console.log(value);
                }}{" "}
              </ProductConsumer>{" "}
            </div>{" "}
          </div>{" "}
        </div>{" "}
      </React.Fragment>
    );
  }
}

这是我的 data.js:

/* 
https://www.iconfinder.com/icons/1243689/call_phone_icon
Creative Commons (Attribution 3.0 Unported);
https://www.iconfinder.com/Makoto_msk */

export const storeProducts = [{
    id: 1,
    title: "Google Pixel - Black",
    img: "img/product-1.png",
    price: 10,
    company: "GOOGLE",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
}, {
    id: 2,
    title: "Samsung S7",
    img: "img/product-2.png",
    price: 16,
    company: "SAMSUNG",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
}, {
    id: 3,
    title: "HTC 10 - Black",
    img: "img/product-3.png",
    price: 8,
    company: "htc",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
}, {
    id: 4,
    title: "HTC 10 - White",
    img: "img/product-4.png",
    price: 18,
    company: "htc",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
}, {
    id: 5,
    title: "HTC Desire 626s",
    img: "img/product-5.png",
    price: 24,
    company: "htc",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
}, {
    id: 6,
    title: "Vintage Iphone",
    img: "img/product-6.png",
    price: 17,
    company: "apple",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
}, {
    id: 7,
    title: "Iphone 7",
    img: "img/product-7.png",
    price: 30,
    company: "apple",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
}, {
    id: 8,
    title: "Smashed Iphone",
    img: "img/product-8.png",
    price: 2,
    company: "apple",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
}];

export const detailProduct = {
    id: 1,
    title: "Google Pixel - Black",
    img: "img/product-1.png",
    price: 10,
    company: "google",
    info: "Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
    inCart: false,
    count: 0,
    total: 0
};

【问题讨论】:

    标签: reactjs fetch state


    【解决方案1】:

    您似乎没有实际上为您的应用提供上下文值。提供者需要包装 children 属性以便向他们提供任何东西。

    class ProductProvider extends React.Component {
      state = {
        products: storeProducts,
        detailProduct: detailProduct
      };
    
      handleDetail = () => {
        console.log("hello products");
      };
    
      addToCart = () => {
        console.log("hello details");
      };
    
      render() {
        return (
          <ProductContext.Provider
            value = {{
              ...this.state,
              handleDetail: this.handleDetail,
              addToCart: this.addToCart
            }}
          >
            {this.props.children} // <-- render children sub-tree
          </ProductContext.Provider>
        );
      }
    }
    

    更新

    添加运行代码和框

    【讨论】:

    • 是的,我做到了,但随后出现错误:“渲染不是方法”再次
    • @sugasunshie 您的代码与我的修复似乎呈现正常。检查我在答案中添加的codesandbox。除了问题中包含的内容之外,您的代码中可能还有其他问题。
    • 您好,先生,非常感谢您为我提供的帮助。我添加了映射函数来映射 ProductList 中的每个产品,但它不会再次呈现产品。你能再帮我一次真是太好了!非常感谢这是我的代码框的链接:codesandbox.io/s/…
    • @sugasunshie 您不会从ProductsList 中的地图回调中重新调整任何内容。换句话说,您需要在映射回调函数中使用return &lt;Product key={product.id} product={product} /&gt;;codesandbox.io/s/…
    • 您好先生,我应该在inCart值为false时显示图标,但现在我的购物车图标没有显示,如果您能再次帮助我,那就太好了.顺便说一句,对不起,如果我的工作打扰了你。这是我的密码箱链接:codesandbox.io/s/…
    【解决方案2】:

    通过 context.products 访问您的数据 这是一个例子

    <ProductContext.Provider value={{ products: storeProducts }}>
       {this.props.children}
    </ProductContext.Provider>
    

    在您的产品列表中

    <ProductConsumer>
        {(context) => (
          <React.Fragment>
            <div className="py-5">
              <div className="container">
                {context.products.map((element) => (
                  <p>{element.title}</p>
                ))}
              </div>
            </div>
          </React.Fragment>
        )}
    </ProductConsumer>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      相关资源
      最近更新 更多