React.js 內的 Context api


React context api 在 16.3 或更新版本中安全生產使用。新增 context api 的原因是為了避免在有多個子元件時傳遞道具。

如果不使用 context api,那麼我們必須透過所有中間元件來傳遞道具。另一種備選解決方案是使用諸如 Redux 的第三方庫來維護中央儲存。

理解傳遞道具的問題

App.js → props for books → BookList.js → 再次將 books 傳遞為道具 → Book.js

隨著子元件數量的增加,傳遞道具的鏈條也隨之增加。

使用 context api,react 提供提供者使用者方法來解決此問題。

Creating the context:
BaseContext.js
import React from 'react';
// this is the same to the createStore method of Redux
const BaseContext = React.createContext();
export default BaseContext;

建立提供者

import BaseContext from './BaseContext';
class BookProvider extends Component {
   state = {
      books: {
         book1: { name: 'React', price: 500 },
         book2: { name: 'Angular', price: 450 }
      }
   };
   render() {
      return (
         <BaseContext.Provider
            value={{
               books: this.state.books,
               incrementPrice: selectedID => {
                  const books = Object.assign({}, this.state.books);
                  books[selectedID].price =books[selectedID].price + 1;
                  this.setState({
                     books
                  });
               },
               decrementPrice: selectedID => {
                  const books = Object.assign({}, this.state.books);
                  books[selectedID].price =books[selectedID].price - 1;
                  this.setState({
                     books
                  });
               }
            }}
         >
         {this.props.children}
         </BaseContext.Provider>
      );
   }
}

App.js

class App extends Component {
   render() {
      return (
         <BookProvider>
            <div className="App">
               <header className="App-header">
                  <h1 className="App-title">Welcome to my book store</h1>
               </header>
               <ProductBookList />
            </div>
         </BookProvider>
      );
   }
}

在子元件中,我們可以使用使用者 −

const Books = () => (
   <BaseContext.Consumer>
      {context => (
         <Fragment>
            <h4>Books:</h4>
            {Object.keys(context.books).map(bookID => (
               <Car
                  key={bookID}
                  name={context.books[bookID].name}
                  price={context.books[bookID].price}
                  incrementPrice={() =>context.incrementPrice(bookID)}
                  decrementPrice={() =>context.decrementPrice(bookID)}
               />
            ))}
         </Fragment>
      )}
   </BaseContext.Consumer>
);

使用 context api 我們可以避免在 React 子元件中傳遞道具。

更新於: 2019 年 9 月4 日

810 次檢視

開啟你的職業生涯

完成課程,獲取認證

開始
廣告
© . All rights reserved.