【问题标题】:React Context API trouble with displaying specific items details page显示特定项目详细信息页面的反应上下文 API 问题
【发布时间】:2020-04-04 01:50:21
【问题描述】:

我是 React 新手,正在尝试了解 Context api。现在我有一个显示项目列表的组件。我还有一个组件可以显示有关该项目的详细信息。我想要做的是当我单击某个项目时,显示组件会显示该项目的信息。这是我当前的代码。我目前收到一个错误,即我的 Product.js 文件中未定义状态。

PRODUCTS.JS
import React, { Component } from 'react';
import './App.css';
import { MyProvider, MyContext } from "./Context";
import { Link } from 'react-router-dom';

class Products extends Component {

  render() {
    const { id } = this.state.products
    return (
      <div className="products-list">
        <div className="showcase">
          <MyContext.Consumer>
            {(context) => (
              <React.Fragment>
                {context.state.products.map(item => {
                  return (
                    <Link to="/ProductOverview" style={{ textDecoration: 'none', color: 'inherit' }}>
                    <div onClick={() => context.productDetail(id)} className="showcase-card" style={{ backgroundImage: `url(${item.bgUrl})`}}>
                      <article key={item.id}>
                        <h6>{item.info}</h6>
                      </article>
                    </div>
                    </Link>
                      );
                  })}
              </React.Fragment>
            )}
          </MyContext.Consumer>
        </div>
      </div>
    )
  }
}

export default Products;


CONTEXT.JS
import React, {Component } from 'react';


export const MyContext = React.createContext();

export class MyProvider extends Component {
  state = {
    products: [
      {
        info: "Toy Car",
        id: '0001'
      },
      {
        info: "Toy Truck",
        id: '0002'
      },
      {
        info: "Toy Plane",
        id: '0003'
      },
      {
        info: "Toy Boat",
        id: '0004'
      }
    ]
  };

  getItem = id => {
    const products = this.state.products.find(item => item.id === id);
    return products;
  };

  productDetail = id => {
    const products = this.getItem();
    this.setState(() => {
      return { products };
    });
  };

  render() {
    return (
      <MyContext.Provider value={{
          state: this.state,
        productDetail: this.productDetail}}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}


PRODUCTOVERVIEW.JS

import React, { Component } from 'react';
import './App.css';
import { MyProvider, MyContext } from "./Context";


class ProductOverview extends Component {

  render() {
    return (
      <MyContext.Consumer>
        {(context) => {
          const {id, info} = context;
        return (
          <h1>{info}</h1>
        )
        }}
      </MyContext.Consumer>
    )
  }
};

export default ProductOverview;

【问题讨论】:

    标签: reactjs react-context


    【解决方案1】:

    您需要指定一个状态才能定义和使用它。 在组件的开头,指定状态:

    class Products extends Component {
    state = {
       yourState:6
    }
    render() {
    

    【讨论】:

    • 我不明白为什么我需要在开头指定状态,MyContext.Consumer 不是在引入状态吗?
    【解决方案2】:
    const { id } = this.state.products
    

    您的 Products 组件中没有状态。为了访问上下文存储中的数据,您必须在消费者中使用箭头功能。

    因此,上下文 api 背后的想法是,您将状态存储在上下文对象中,并且该对象带有 2 个组件。供应商和消费者。

    Provider:Provider 将提供应用程序的所有信息。我们将在我们的应用程序之上设置提供程序,如下所示:

    index.js

    import { MyProvider } from "./Context";
    ReactDOM.render(
      <MyProvider>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </MyProvider>,
      document.getElementById("root"));
    

    消费者:将使用提供商提供的信息。我们可以在应用程序中的任何位置获取信息。

    这就是您从提供者返回的内容。

    value={{
              state: this.state,
            productDetail: this.productDetail}}
    

    value 属性是一个对象。这是您应该在组件中访问的方式:

    <MyContext.Consumer>
            {(context) => {
            //context is the object that is returned by the Provider
            //inside state you have products array and you need to choose one of those elements inside the array. lets say you wanna select the first element which is the 0 index.
    
              const {id, info} = context.state.products[0];
            return (
              <h1>{info}</h1>
            )
            }}
          </MyContext.Consumer>
    

    【讨论】:

    • 这一行&lt;div onClick={() =&gt; context.productDetail(id)}返回一个id未定义的错误
    • 我编辑了评论。这应该可以,但我觉得你想渲染产品。究竟想做什么?我
    • 基本上,当我单击 Product.js 中的产品时,链接会将我带到 ProductOverview.js。我希望 ProductOverview 显示我点击的产品的信息。
    • 所以在产品页面中,您想要映射所有产品。所以您需要创建 Product 或作为 ProductDetails 组件。如果你清楚地更新你的问题,我会编辑答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多