仿簡書react項目

仿簡書react項目

本項目地址仿照簡書網站,也是我使用react的第一個完整項目。對有一定react基礎的同學非常友好,非常適合入門學習。零基礎的同學可以參考我的另外一篇文章react_demo。可以通過git log,查看我的學習思路,與我一起學習,一起進步。😀😀

項目使用相關技術和用途

  • 使用官方提供腳手架create-react-app初始化項目
  • 數據狀態管理使用redux
  • 將數據狀態綁定到react使用react-redux
  • 路由跳轉使用react-router-dom
  • 動畫交互使用styled-components
  • 異步加載組件使用react-loadable

項目使用及運行

git clone [email protected]:sunhangye/react_demo.git

cd react_demo

yarn

yarn start # 瀏覽器自動打開localhost:3000

yarn build # 上線

##開發過程筆記

styled-components 使用3+版本對用api使用injectGlobal

使用react-transition-group 過渡動畫

使用CSSTransition組件傳入三個屬性值

  • in: boolean 執行狀態
  • timeout obj:200 延時時間
  • classNames strng: slide 在css中定義 slide-enter、slide-enter-active、slide-exit、slide-exit-active
 &.slide-enter {
   transition: all .2s ease-out;
 }
 &.slide-enter-active {
   width: 240px;
 }
 &.slide-exit {
   transition: all .2s ease-out;
 }
 &.slide-exit-active {
   width: 160px;
 }

redux-thunk

在redux中action正常返回 object{type:changeDataAction,data}

而redux-thunk 可以返回異步函數 () => {return(dispatch) {axios.get()} }

使用高級組件

react render會執行兩次 一次是初始化state,第二次是更新state,所以爲避免多次渲染使用, 將之前Component替換爲PurComponent

梳理下數據改變、視圖更新流程

  1. 在reducer中初始化articlePage
  2. 利用react-redux connect,將state與組件做關聯取出articlePage賦值到組件的props,數據放到jsx模板中展示出來
  3. 點擊加載更多按鈕觸發點擊事件onClock={()=>{getMoreList(page)}}將page傳到參數中
  4. 派發action dispatch(actionCreators.getMoreList(page))
  5. 在actionCreators中定義action {type:ADD_HOME_LIST, page: page}
  6. 使用react-thunk 進行異步操作 請求數據後dispatch action
  7. 在reducer中接收到action 通過immutablejs 語法 改變page和articleList 返回一個新的state
  8. 組件接到state自動重新視圖層

數據嵌套問題

防止html出現便籤,在組件中加上屬性props dangerouslySetInnerHTML={{__html:item}}

路由

  1. 動態路由 / 反斜槓 /id= 然後可以this.props.match.param獲取ID
  2. 參數傳遞 id= 從this.props.location.search?id=1,然後進行處理

###dom獲取
使用styled-components獲取真實dom應使用innerRef

異步加載組件

使用react-loadable。 將detail異步加載,但detail獲取不到match對象,因此使用react中的withRouter

高階組件中的withRouter, 作用是將一個組件包裹進Route裏面, 然後react-router的三個對象history, location, match就會被放進這個組件的props屬性中.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章