React實戰篇(React仿今日頭條)

前言

上次初學用 react 寫了個後臺管理,此次便尋思寫個移動端的項目。便有了此次的這個項目。html

這個項目之前寫了個 vue 的版本。有興趣的能夠 點擊進入vue


模擬數據用的是 Easy Mockreact

用的是我之前寫 vue-toutiao 用到的數據webpack

帳號: vue-toutiaoios

密碼: 123456git

技術棧

react + react-redux + react-router + webpackgithub

結構:

  • build: webpack配置
  • config: 項目配置參數
  • src
    1. actions: 存放 action 方法
    2. assets: 靜態資源文件,存放圖片啥的
    3. components: 經常使用組件
    4. reducers: 存放 reducer
    5. router: 路由管理
    6. store: 狀態管理 redux
    7. styles: 樣式文件
    8. utils: 經常使用封裝
    9. views: 視圖頁面
  • static: 靜態文件: 存放 favicon.ico 等等

效果演示

圖片描述

圖片描述

知識點

按需加載

經過 import() 方法加載組件, 在經過高階組件處理 import 返回的 Promise 結果。web

// asyncComponent.js
import React from 'react'

export default loadComponent => (
    class AsyncComponent extends React.Component {
        state = {
            Component: null,
        }
        async componentDidMount() {
            if (this.state.Component !== null) return
            try {
                const {default: Component} = await loadComponent()
                this.setState({ Component })
            }catch (err) {
                console.error(`Cannot load component in <AsyncComponent />`);
                throw err
            }
        }

        render() {
            const { Component } = this.state
            return (Component) ? <Component {...this.props} /> : null
        }
    }
)

複製代碼

以下使用npm

import asyncComponent from './asyncComponent'
const Demo = asyncComponent(() => import(`views/demo.js`))
<Route path="/demo" component={Demo}/>
複製代碼

路由設置

統一配置路由,及路由狀態redux

import asyncComponent from './asyncComponent'
const _import_views = file => asyncComponent(() => import(`views/${file}`))
export const loyoutRouterMap = [
    { 
        path: '/', 
        name: '首頁', 
        exact: true,
        component: _import_views('Home')
    },
    { 
        path: '/video', 
        name: '視頻',
        component: _import_views('Video')
    },
    { 
        path: '/headline', 
        name: '微頭條',
        component: _import_views('Headline')
    },
    { 
        path: '/system', 
        name: '系統設置',
        auth: true, 
        component: _import_views('System')
    }
] 
複製代碼

登陸攔截

經過路由配置中 auth 屬性來判斷是否須要登陸 如如下配置

{ 
    path: '/system', 
    name: '系統設置',
    auth: true, 
    component: _import_views('System')
}
複製代碼

登錄配置及判斷

// authRoute.js
import React from 'react'
import store from '../store'
import { Route, Redirect } from 'react-router-dom'

export default class extends React.Component {
    render () {
        let {component: Component, ...rest} = this.props
        // 是否登陸
        if (!store.getState().user.user.name) {
            return <Redirect to='/login' />
        }
        return <Route {...rest}  component={Component}/>
    }
}


// 生成route
const renderRouteComponent = routes => routes.map( (route, index) => {
    if (route.auth) { // 須要權限登陸
        return <AuthRoute key={index} {...route}/>
    }
    return <Route key={index} {...route}/>
})
複製代碼

路由動畫

經過 react-router-transition 作的切換動畫。

而後經過 history.slideStatus 來判斷如何動畫

react-router-transition 具體API

redux-thunk處理action異步

redux-actions 來書寫 action 跟 reducer

// action.js
import { createAction } from 'redux-actions'
import axios from 'utils/axios'
export const getHeadlineList = (params) => dispatch => {
    return new Promise( (resolve, reject) => {
        axios.get('headline/list', params)
            .then( res => {
                const list = res.data.list
                dispatch(createAction('GET_HEADLINE_LIST')(list))
                resolve(list)
            }).catch( err => {
                reject(err)
            })
    })
}

// reducer.js
import { handleActions } from 'redux-actions'
import { combineReducers } from 'redux'
const state = {
    headlineList: []
}
const headline = handleActions({
    GET_HEADLINE_LIST: (state, action) => {
        let list = action.payload
        state.headlineList = state.headlineList.concat(list)
        return {...state}
    }
}, state)
export default combineReducers({
    headline
})

// store.js  
// redux-thunk配置
import { createStore, compose, applyMiddleware  } from 'redux'
import reducer from '../reducers'
import thunk from 'redux-thunk'
const configureStore => createStore(
    reducer,
    compose(
        applyMiddleware(thunk)
    ) 
)
export default configureStore()

複製代碼

還有一些零零散散的知識點,就不介紹了,具體能夠到 github 上查看。

github

我的博客

在線觀看地址

相關文章
相關標籤/搜索