反应上下文:状态流从提供者到消费者

时间:2020-05-24 15:43:45

标签: reactjs

我想尝试使用Consumer和Provider通过多个组件从状态转移记录。我在ShoppingBasketProvider组件中有一个要传递给ShoppingBasket组件的值,但目前它不输出任何值,并且等于未定义。告诉我我在做什么错。

enter image description here

我有下一个组成部分:

ShoppingBasketContext:

import React, { Component, PureComponent } from "react";

export const ShoppingBasketContext = React.createContext();

export default class ShoppingBasketProvider extends Component {
  state = {
    shoppingBasketItems: 11
  }

  render() {
    return (
      <ShoppingBasketContext.Provider shoppingBasketItems={ this.state.shoppingBasketItems }>
        {this.props.children}
      </ShoppingBasketContext.Provider>
    )
 }
}

app:

import React, {PureComponent} from 'react'
import './App.scss';
import Shop from '../../page/shop/shop.js'
import AboutUs from '../../page/aboutUs/aboutUs.js'
import Menu from '../menu/menu.js'
import ShoppingBasketProvider from '../shoppingBasketProvider/shoppingBasketProvider.js'
import { BrowserRouter, Switch, Route, Redirect, Router } from "react-router-dom";

export default class App extends PureComponent {


  render() {
    return (
      <main>
          <ShoppingBasketProvider>
            <BrowserRouter>
              <Menu />
              <Switch>
                <Route path="/" exact children={<Shop />} />
                <Route path="/aboutus" children={<AboutUs />} />
                <Redirect to="/" />
              </Switch>
            </BrowserRouter>
          </ShoppingBasketProvider>
      </main>
    );
  }
}

购物篮:

import React, {PureComponent} from 'react'

import { ShoppingBasketContext } from '../shoppingBasketProvider/shoppingBasketProvider.js';

export default class ShoppingBasket extends PureComponent {
  render() {
    return (
      <div>
        <ShoppingBasketContext.Consumer>
          {shoppingBasketItems => (
            <React.Fragment>
              Shopping cart: <span>{shoppingBasketItems}</span>
            </React.Fragment>
          )}
        </ShoppingBasketContext.Consumer>
      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:2)

您传递给提供者的道具必须称为值。参见下面的建议更改

return (
      <ShoppingBasketContext.Provider value={ this.state.shoppingBasketItems }>
        {this.props.children}
      </ShoppingBasketContext.Provider>
    )