web-dev-qa-db-ja.com

レンダリング外のReact Context Consumerからデータを取得する方法

私は新しいReact Context APIを使用していますが、ConsumerデータをContext.Consumer変数から取得する必要があり、renderメソッド内で使用しないでください。とにかくこれを達成できますか?

私が欲しいものを例証するために:

console.log(Context.Consumer.value);

これまでにテストしたこと:上記の例では、Context.Consumer currentValueおよびContext Consumerが持っている他の変数をテストし、Context.Consumer()を関数として実行しようとしましたが、何も機能しませんでした。

何か案は?

14

更新

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

ただし、コンポーネントは単一のコンテキストにのみアクセスできます。複数のコンテキスト値を使用するには、レンダープロップパターンを使用します。 Class.contextType の詳細。

実験的な パブリッククラスフィールドの構文 を使用している場合、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);
22
Shubham Khatri