gpt4 book ai didi

javascript - 如何通过重构从 Context.Consumer 访问值?

转载 作者:行者123 更新时间:2023-12-03 00:27:04 25 4
gpt4 key购买 nike

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

您如何通过重构访问消费者数据?

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:

Edit 8z18469pj2

关于javascript - 如何通过重构从 Context.Consumer 访问值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54043615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com