zoukankan      html  css  js  c++  java
  • [React] Use the new React Context API

    The React documentation has been warning us for a long time now that context shouldn't be used and that the API is unstable. Well, with the release of React 16.3, we're finally getting a stable context API and what's even better is that it has received a makeover and the dev experience is fantastic! In this lesson, we'll look at an example app that passes props down several levels deep into the component tree and replace all that prop drilling with the new context API. We'll see how to create a Provider and a Consumer, how to use them in the code and we'll take a look at how the default properties that get passed into createContext come into play.

    A condition that we need 'context' API is to avoid pass Props all the way down to the component tree.

    For example:

    So porps are passed all the way down from 

      PageWrapper

              -- ProfileWrapper

          -- ProfileDetails

    New context API looks like this:

    1. Create an Context service:

    import { createContext } from "react";
    
    const ProfileContext = createContext({
      firstName: "Sally",
      lastName: "Anderson"
    });
    
    export const ProfileProvider = ProfileContext.Provider;
    
    export const ProfileConsumer = ProfileContext.Consumer;

     'createContext' takes an default value. 

    2. Wrap the top level component into Provider:

    import { ProfileProvider } from "./ProfileContext";
    
      render() {
        return (
          <ProfileProvider value={this.state.profile}>
            <PageWrapper />
          </ProfileProvider>
        );
      }

    If you want to just use default value, don't provide the Provider... this approach is a little bit strange.

      render() {
        return (
          <PageWrapper /> // may change in release
        );
      }

    3. Remove all the props passed down.

    4. In the component which do need context, use Consumer, Cunsumer takes a function as child.

    import React from "react";
    import { ProfileConsumer } from "./ProfileContext";
    
    export const ProfileDetails = props => (
      <ProfileConsumer>
        {context => (
          <div>
            <div>
              <strong>First name:</strong> {context.firstName}
            </div>
            <div>
              <strong>Last name:</strong> {context.lastName}
            </div>
          </div>
        )}
      </ProfileConsumer>
    );

  • 相关阅读:
    01视频传输,监控,直播方案摄像头如何采集的图像,MCU如何读取的图像数据
    203ESP32_SDK开发softAP+station共存模式
    2视频传输,监控,直播方案搭建视频流服务器,推送视频流,拉取视频流观看(RTMP,m3u8)
    F# (Part one)
    测试驱动开发(一)我们要的不仅仅是“质量”
    软件开发中的破窗效应
    结对编程神奇的力量
    《高性能网站建设指南》笔记
    【线程呓语】Thread
    【线程呓语】与线程相关的一些概念
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8454745.html
Copyright © 2011-2022 走看看