如何在<provider>中使用另一个<consumer>?

时间:2018-12-14 00:40:29

标签: javascript reactjs

./ App.js

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from './context.js';
import { Provider as Provider2 } from './context2.js';
import Child from './Child.js';

import "./styles.css";

class App extends React.Component {
    render () {
        return (
            <Provider number={1}>
                <Provider2 number2={2}>
                    <Child/>
                </Provider2>
            </Provider>
        );
    }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

./ Child.js

import React from 'react';
import { Consumer } from './context.js';

class Child extends React.Component {
    render() {
        return (
            <Consumer>
                {(value) => (
                    <div>{value.number}</div>
                )}
            </Consumer>
        );
    }
}

export default Child;

./ context.js

import React, { createContext } from 'react';
import { Consumer as Consumer2 } from './context2.js';

const Context = createContext(undefined),
      Consumer = Context.Consumer;

class Provider extends React.Component {
    render () {
        return (
            <Consumer2>
                {(value) => (
                    <Context.Provider value={{ number:(this.props.number + value.number2) }}>
                        {this.props.children}
                    </Context.Provider>
                )}
            </Consumer2>
        );
    }
}

export { Consumer, Provider };

./ context2.js

import React, { createContext } from 'react';

const Context = createContext(undefined),
      Consumer = Context.Consumer;

class Provider extends React.Component {
    render () {
        return (
            <Context.Provider value={{ number2:this.props.number2 }}>
                {this.props.children}
            </Context.Provider>
        );
    }
}

export { Consumer, Provider };

您好,如您所见 context.js ,我在 中使用 Consumer2 提供商 。 但出现错误 值未定义

当我将 Provider2 放入 Provider 时,效果很好。

但是我想从服务器设置一个值,所以我必须在 App.js 中使用 Provider2 >。

您可以在https://codesandbox.io/s/py5jrj8n07上进行测试。

有什么好主意吗?感谢您的阅读:)

1 个答案:

答案 0 :(得分:1)

Provider尝试消耗Provider2的值。在index.js(App)文件中,您必须切换提供程序的位置,以使它们能够以正确的顺序使用。 Provider2不会消耗Provider,因此应该可以使用:

<Provider2 number2={2}>
  <Provider number={1}>
    <Child />
  </Provider>
</Provider2>