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