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 子元件中傳遞道具。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP