react——context

前言

Context被翻譯爲上下文,在編程領域,這是一個常常會接觸到的概念,React中也有。html

在React的官方文檔中,Context被歸類爲高級部分(Advanced),屬於React的高級API,但官方並不建議在穩定版的App中使用Context。react

The vast majority of applications do not need to use content.web

If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.編程

不過,這並不是意味着咱們不須要關注Context。事實上,不少優秀的React組件都經過Context來完成本身的功能,好比react-redux的<Provider />,就是經過Context提供一個全局態的store,拖拽組件react-dnd,經過Context在組件中分發DOM的Drag和Drop事件,路由組件react-router經過Context管理路由狀態等等。在React組件開發中,若是用好Context,能夠讓你的組件變得強大,並且靈活。redux

今天就想跟你們聊一聊,我在開發當中,所認識到的這個Context,以及我是如何使用它來進行組件開發的。react-router

注:本文中全部提到的App皆指Web端App。app

初識React Context

官方對於Context的定義

React文檔官網並未對Context給出「是什麼」的定義,更可能是描述使用的Context的場景,以及如何使用Contextide

官網對於使用Context的場景是這樣描述的:this

In Some Cases, you want to pass data through the component tree without having to pass the props down manuallys at every level. you can do this directly in React with the powerful "context" API.翻譯

簡單說就是,當你不想在組件樹中經過逐層傳遞props或者state的方式來傳遞數據時,能夠使用Context來實現跨層級的組件數據傳遞。

 
image

使用props或者state傳遞數據,數據自頂下流。

 
image

使用Context,能夠跨越組件進行數據傳遞。

 

參考:https://www.jianshu.com/p/eba2b76b290b

官網:https://react-1251415695.cos-website.ap-chengdu.myqcloud.com/docs/context.html

相關文章
相關標籤/搜索