React+Redux項目實戰總結

本項目實戰是簡化版的大衆點評wap版html

技術棧

react + redux + react-router-dom
mock數據使用的是 koa + koa-routernode

項目源碼:https://github.com/volcanoliuc/dianpingappreact

項目結構

├── app    #項目主目錄
│ ├── index.jsx    # 項目的入口index
│ ├── index.tmpl.html    # html生成模板
│ ├── actions    # redux action
│ ├── component    # 組件文件夾(木偶組件)
│ ├── config
│ ├── contianer    # 組件文件夾(智能組件)
│ │ ├── index.jsx
│ │ ├── 404.jsx    # 404頁面
│ │ ├── City    # 選擇城市
│ │ ├── Detail    # 商戶詳情頁
│ │ ├── Home    # 首頁
│ │ ├── Login    # 登陸頁
│ │ ├── Search    # 搜索結果頁
│ │ └── User    # 用戶中心頁
│ ├── contant    # actionType
│ ├── fetch    # 請求服務API
│ ├── config
│ ├── reducers
│ ├── router    #路由配置
│ ├── static    # 靜態文件
│ ├── store
│ └── util    # 工具方法
├── docs
├── mock    # mock數據
│ ├── server.js
│ └── ...
└── testgit

遇到的問題及解決方法

1.react-router-dom 4.0
路徑跳轉問題:
react-router-dom 4.0沒法經過導入browserHistory進行跳轉github

解決方案一:
經過react-router-dom history進行跳轉:this.props.history.push('/')npm

  • 配置在Route下的組件能夠直接調用this.props.history
  • 未配置在Route下的組件須要用withRouter高階組件把組件包裹起來
import {withRouter} from 'react-router-dom'
... 
class App extends React.Component{
  handleClick(){
    this.props.history.push('/')
  }
  ...
}
export default withRouter(App)

解決方法二:
react-router v4 在 Router 組件中經過Context暴露了一個router對象,能夠在子組件中使用Context獲取router對象,由於react不推薦使用Context,因此這種方法慎用,具體實現自行搜索 - -#redux

2.node後端接收post請求參數
1、koa後端沒法直接讀取post傳過去的參數因此須要定義一個方法去解析post參數。後端

//解析傳入的post參數
const parsePostData = ( ctx ) =>  {
  return new Promise((resolve, reject) => {
    try {
      let postdata = "";
      ctx.req.addListener('data', (data) => {
        postdata += data
      })
      ctx.req.addListener("end",function(){
        let parseData = parseQueryStr( postdata )
        resolve( parseData )
      })
    } catch ( err ) {
      reject(err)
    }
  })
}
//把傳入的參數解析成對象
const parseQueryStr = ( queryStr ) =>  {
  let queryData = {}
  let queryStrList = queryStr.split('&')
  console.log( queryStrList )
  for (  let [ index, queryStr ] of queryStrList.entries()  ) {
    let itemList = queryStr.split('=')
    queryData[ itemList[0] ] = decodeURIComponent(itemList[1])
  }
  return queryData
}

只須要把koa ctx 直接傳入parsePostData就能夠獲得一個post請求的參數react-router

let postData = await parsePostData( ctx )app

2、使用koa-bodyparser中間件
對於POST請求的處理,koa-bodyparser中間件能夠把koa2上下文的formData數據解析到ctx.request.body中

npm install --save koa-bodyparser@3  //安裝

...
// 使用ctx.body解析中間件
app.use(bodyParser())
...
let postData = ctx.request.body

更多關於koa的學習資料能夠參考Koa2進階學習筆記

總結

本次項目從零配置整個項目的結構,主要是讓本身了從新理解了react + redux + react-router 全家桶開發模式。

相關文章
相關標籤/搜索