[React] Use the new React Context API

來源:互聯網
上載者:User

標籤:ase   ram   san   lease   ops   may   you   service   reac   

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>);

 

[React] Use the new React Context API

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.