如何在渲染之外从 React Context Consumer 获取数据

IT技术 reactjs react-context
2021-04-08 02:28:04

我正在使用新的 React Context API,我需要从 Context.Consumer 变量中获取消费者数据,而不是在渲染方法中使用它。无论如何,我可以做到这一点吗?

例如我想要什么:

console.log(Context.Consumer.value);

到目前为止我测试的内容:上面的示例测试了 Context.Consumer currentValue 和 Context Consumer 拥有的其他变量,尝试将 Context.Consumer() 作为函数执行,但没有任何效果。

有任何想法吗?

5个回答

更新

React v16.6.0 开始,您可以使用上下文 API,例如:

class App extends React.Component {
    componentDidMount() {
       console.log(this.context);
    }
    render() {
       // render part here
       // use context with this.context
    }
}
App.contextType = CustomContext

但是,该组件只能访问单个上下文。为了使用多个上下文值,请使用渲染props模式。更多关于Class.contextType

如果您使用的是实验性公共类字段语法,则可以使用静态类字段来初始化您的contextType

class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}

渲染props模式

当我从问题中了解到,要在组件内部但在渲染外部使用上下文时,请创建一个 HOC 来包装组件:

const WithContext = (Component) => {
  return (props) => (
      <CustomContext.Consumer>
           {value =>  <Component {...props} value={value} />}
      </CustomContext.Consumer>
  )
}

然后使用它:

class App extends React.Component {
    componentDidMount() {
       console.log(this.props.value);
    }
    render() {
       // render part here
    }
}
export default WithContext(App);
@MenaiAlaEddine MyContext 是您使用 React.createContext 创建的上下文
2021-05-24 02:28:04
这或多或少是来自reactjs.org/docs/的官方问题…… 但是我发现这个解决方案比旧this.context的 React 15 更复杂和样板
2021-05-30 02:28:04
@ShubhamKhatri,MyContextstatic contextType = MyContext;是什么?
2021-06-04 02:28:04
@LucaFabbri,从 React 16.6.0 版本开始,可以使用上下文 API,this.context因此不再需要 BoilerPlate
2021-06-08 02:28:04
@ShubhamKhatri,我不知道为什么 16.6+App.contextType = CustomContext对我不起作用。它什么也没做。static contextType只有当你有1个上下文工作。然而,WithContext 就像一个魅力!为你鼓掌。
2021-06-13 02:28:04

您可以使用useContextHook在功能组件中实现这一点

您只需要从初始化它的文件中导入上下文。在这种情况下,DBContext.

 const contextValue = useContext(DBContext);

您可以通过不受支持的吸气剂:

YourContext._currentValue

请注意,它仅在渲染期间有效,在异步函数或其他生命周期事件中无效。

这就是它可以实现的方式。

 class BasElement extends React.Component {
  componentDidMount() {
    console.log(this.props.context);
  }

  render() {
    return null;
  }
}

const Element = () => (
  <Context.Consumer>
    {context =>
      <BaseMapElement context={context} />
    }
  </Context.Consumer>
)

要使@wertzguy 解决方案起作用,您需要确保您的商店定义如下:

// store.js
import React from 'react';

let user = {};
const UserContext = React.createContext({
  user,
  setUser: () => null
});

export { UserContext };

然后你可以做

import { UserContext } from 'store';

console.log(UserContext._currentValue.user);