繁体   English   中英

如何使用recompose从Context.Consumer访问值?

[英]How do access a value from Context.Consumer with recompose?

我用React Context API传递了一些数据,我尝试从重组方法内部访问它

您以哪种方式重组并使用了Consumer's数据?

import React from "react";
import { MyContext } from "./index";
import { fromRenderProps, withProps, compose } from "recompose";

const enhance = compose(
    /**
     * @todo add 'Mr.' to each name
     */
    withProps(/** How do I get "names" from Consumer here? */)
);

const GrandChild = props => {
    return (
        <MyContext.Consumer>
            {names => {
                console.log(names)
                return (
                    <div>
                        <h2>GrandChild</h2>
                        {names.map((name, index) => (<li key={index}>{name}</li>))}
                    </div>
                );
            }}
        </MyContext.Consumer>
    );
};

export default enhance(GrandChild);

实时代码: https : //codesandbox.io/s/k0xm2vlw8r

这是解决此问题的一种方法:

GrandChild.js

import React from "react";
import { MyContext } from "./index";
import { withProps, compose } from "recompose";

const enhance = compose(
  withProps(({ names }) => ({ reshapedNames: ["this first", ...names] }))
);

const GrandChild = props => {
  return (
    <div>
      <h2>GrandChild</h2>
      {props.reshapedNames.map((name, index) => (
        <li key={index}>{name}</li>
      ))}
    </div>
  );
};
const EnhancedGrandChild = enhance(GrandChild);
const EnhancedGrandChildWithContext = props => {
  return (
    <MyContext.Consumer>
      {names => <EnhancedGrandChild names={names} {...props} />}
    </MyContext.Consumer>
  );
};
export default EnhancedGrandChildWithContext;

只需添加一个单独的图层即可提供上下文。

这是CodeSandbox:

编辑8z18469pj2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM