【问题标题】:How to get the data from React Context Consumer outside the render如何从渲染之外的 React Context Consumer 获取数据
【发布时间】:2018-09-26 22:45:08
【问题描述】:

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

举例说明我想要什么:

console.log(Context.Consumer.value);

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

有什么想法吗?

【问题讨论】:

  • 我测试了一个类似的方法,消费者内部有一个_currentValue和_defaultValue成员,但访问Context.Consumer._currentValue.value总是返回默认值,如果没有正确初始化,则返回未定义。
  • 我创建了一个 HOC npmjs.com/package/react-context-consumer-hoc,它通过在导出之前包装你的组件来实现这一点。它可能不是您要找的东西,但我想把它放在这里,因为这是我第一次遇到这个问题的地方。

标签: reactjs react-context


【解决方案1】:

更新

从 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

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

如果您使用的是实验性public class fields syntax,您可以使用static 类字段来初始化您的contextType:

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

渲染道具模式

当我从问题中了解到,要在组件内部但在渲染外部使用上下文时,请创建一个 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);

【讨论】:

  • 这或多或少是来自 reactjs.org/docs/… 的官方问题,但是我发现这个解决方案比 React 15 的旧 this.context 复杂得多。
  • @LucaFabbri,从 React 的 16.6.0 版本开始,上下文 API 可以使用 this.context,因此不再需要 BoilerPlate
  • @ShubhamKhatri,我不知道为什么 16.6+ App.contextType = CustomContext对我不起作用。它什么也没做。 static contextType 仅在您有 1 个上下文时才有效。然而,WithContext 就像一个魅力!为你鼓掌。
  • @ShubhamKhatri, static contextType = MyContext; MyContext 是什么?
  • @MenaiAlaEddine MyContext 是您使用 React.createContext 创建的上下文
【解决方案2】:

您可以通过useContext Hook 在功能组件中实现这一点。

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

 const contextValue = useContext(DBContext);

【讨论】:

    【解决方案3】:

    您可以通过不受支持的 getter:

    YourContext._currentValue
    

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

    【讨论】:

      【解决方案4】:

      这就是它的实现方式。

       class BasElement extends React.Component {
        componentDidMount() {
          console.log(this.props.context);
        }
      
        render() {
          return null;
        }
      }
      
      const Element = () => (
        <Context.Consumer>
          {context =>
            <BaseMapElement context={context} />
          }
        </Context.Consumer>
      )
      

      【讨论】:

        【解决方案5】:

        要使@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);
        

        【讨论】:

          猜你喜欢
          • 2018-09-23
          • 1970-01-01
          • 2019-04-28
          • 2020-05-31
          • 2021-12-09
          • 1970-01-01
          • 2021-05-11
          相关资源
          最近更新 更多