元芳,你怎么看Redux?

作者: github加星点进来 | 来源:发表于2016-08-11 00:16 被阅读292次

生活不止眼前的苟且,还有诗和远方,远方除了远一无所有。-------反正不是我

<br />

刚接触react,发现还要学redux,感觉推开一扇技术之门,发现是更多的门。没精力写的很细。

网上盗张图


Paste_Image.png

<br />

redux.gif

rang我们一切从0开始,先安装redux react-redux react-router-redux redux-thunk redux-logger --save

这样install redux-thunk 的原因是使用到了异步

Paste_Image.png

接上门课程(http://www.jianshu.com/p/3089495d8532
来继续写

既然是使用了react ,所以可以新建个普通的component ,名字叫Home . 由于写多了swift , 所以习惯写class 类的方法定义component

先上整个class Home代码,直接代码里面注释。不然文章太长。

import React , { Component } from 'react';
//这是Action
import { fetchPosts , fetchRefreshPosts } from '../actions/handle'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

class Home extends Component {

//这是系统钩子,hook,这在swift中很普遍。也很容易理解,在component 特定的时候触发,下面是组件安装完成触发
componentDidMount(){
    console.log(`=componentDidMount=`);
    this.props.fetchPosts()
}

//这是系统钩子,hook,这在swift中很普遍。也很容易理解,
//在component 特定的时候触发,下面是组件更改props的时候触发,
//这个时候不能继续dispatch(派遣)任务。例如。不能使用this.props.fetchRefreshPosts() 方法。不然无限循环。
componentWillReceiveProps(nextProps){
  console.log(`=componentWillReceiveProps=`);
  console.log(nextProps);
}

handlerefreshData(e){
  e.preventDefault()
  //由于mapDispatchToProps了方法,所以可以直接使用this.props.fetchRefreshPosts()
  this.props.fetchRefreshPosts()
}

render(){
  const { json2 , number , isFetching} = this.props
  console.log(`json2===========`)
  console.log(json2);
  const isEmpty = json2.length === 0
  console.log(isFetching);
  return (<div>
    <h3>Home containers <a href='#' onClick={this.handlerefreshData.bind(this)}>刷新o</a></h3>
  <ul >
    //render 自然不必多说,值得一提的是,在map的时候。返回的元素(element) 需要加个Key 。
    //不然会报错。这个ng-repeat 有点像,记得ng-repeat 是不会报错的,如下 key={index}
    {!isEmpty && json2.map((item , index) => {
      return <li key={index}>{number}{item.title}</li>
    })}
  </ul>
  </div>)
}
}

//这2个方法看名字mapStateToProps也知道是把state 的一些方法映射到this.props上面
function mapStateToProps(state){
  return {
    json2 : state.linkf.data || [],
    number : state.linkf.number || 0,
    isFetching : state.linkf.isFetching || true
  }
}
//这2个方法看名字mapDispatchToProps也知道是把Dispatch 的一些方法映射到this.props上面
function mapDispatchToProps(dispatch){
  return {
  fetchPosts : () => {
    dispatch(fetchPosts())
  },
    fetchRefreshPosts : () => {
      dispatch(fetchRefreshPosts())
      }
    }
}

//这里是把json2 , number ,isFetching , fetchPosts ,fetchRefreshPosts
// 等属性和方法 绑定到this.props 上面。这样就
//可以使用 const {json2 , isFetching , fetchPosts} = this.props等

export default connect(mapStateToProps,mapDispatchToProps)(Home)

我们在来读预设的常量

//保存在一个单独的文件,//constant.js
// action常量
export const INCREASE = 'INCREASE'
export const DECREASE = 'DECREASE'
export const LOADDATA = 'LOADDATA'
export const GETSUCCESS = 'GETSUCCESS'
export const REFRESH = 'REFRESH'
export const REFRESHDATA = 'REFRESHDATA'
export const SAVENOTE ='SAVENOTE';
export const SAVENOTESUCCESS ='SAVENOTESUCCESS';

在来个actionCreate

import { INCREASE, DECREASE, GETSUCCESS, REFRESHDATA,SAVENOTE , REFRESH } from './constants'  // 引入action类型名常量
import 'whatwg-fetch';  // 可以引入fetch来进行Ajax;
const ul = `http://api.linked-f.com/test/weixin/lesson?code=Aaaaaaaaaaaa%2CB&openid=wapCode&specialCode=&currentPath=%2Ftest%2Fhtml%2Findex.html&lessonId=632&type=online_info`
const ul2 = `http://api.linked-f.com/test/weixin/lessonlist?code=Aaaaaaaaaaaa%2CB&openid=wapCode&specialCode=&currentPath=%2Ftest%2Fhtml%2Findex.html&type=live_info&limit=10`
// 这里的方法返回一个action对象

//刷新的actionCreate
export const refreshData = () => {
    return {
        type: REFRESHDATA
    }
}
  
//成功的actionCreate
export const getSuccess = (json) => {
  console.log(`getSuccess`)
  console.log(json);
    return {
        type: GETSUCCESS,
        json : json.result.lessonList
    }
}

export const refreshHandle = (json) => {
  console.log(`REFRESH`)
  console.log(json);
    return {
        type: REFRESH,
        json : json.results
    }
}


export function fetchPosts() {
    return dispatch => {
        return fetch(ul)
            .then((res) => { console.log(res.status); return res.json() })
            .then((data) => {
                dispatch(getSuccess(data))
            })
            .catch((e) => { console.log(e.message) })
        }
}

export function fetchRefreshPosts() {
    return dispatch => {
        return fetch(ul2)
            .then((res) => { console.log(res.status); return res.json() })
            .then((data) => {
                dispatch(refreshHandle(data))
            })
            .catch((e) => { console.log(e.message) })
        }
}

在来看最后1个reducer 。 每dispatch一个actionCreate , 系统都自动回reducer,不用你操心数据怎么变,因为我们在createStore 的时候绑定了reduer 。 看如下截图

Paste_Image.png

我们看reducer 代码

// reducers/count.js
import { INCREASE, DECREASE, GETSUCCESS, REFRESHDATA , REFRESH} from '../actions/constants' // 引入action类型常量名

// 初始化state数据
const initialState = {
    id: 1
}

// 通过dispatch action进入
export default function update(state = initialState, action) {

// 根据不同的action type进行state的更新
switch(action.type) {
  

    case GETSUCCESS:
        console.log(`reducer`)
        console.log(action.json)
        let n = Object.assign({}, state, { data: action.json , id : 2 , isFetching : false })
        console.log(n)
        return n
    case REFRESH:
            console.log(`REFRESH`)
            console.log(state)
            let ns = Object.assign({}, state, { data: action.json , id : 3 , isFetching : false})
            console.log(ns)

       return ns
    
    default:
        return state
}
}

reducer 的路口

// reducers/index.js
import { combineReducers } from 'redux' // 利用    combineReducers 合并reducers
import { routerReducer } from 'react-router-redux' // 将routerReducer一起合并管理
import linkf from './count' // 引入update这个reducer

  //这里写linkf 是。在使用state的时候就这样,例如state.linkf.json2。
//reducer 返回最终的数据。总入口写错linkf,当然都可以换其他的。linkf就心json的属性

export default combineReducers({
    linkf,
    routing: routerReducer
})

至此 。action , reducer 都有了。也把store 帮到了component 上面。就可以运行了。

至此这个demo 加上上篇路由,几乎覆盖了前端所有常用的只是点。

文章稿纸的地址详见githubhttps://github.com/976500133/react-router-demo

相关文章

  • 元芳,你怎么看

    元芳,我失败了,你怎么看; 元芳,我终于成功了,你怎么看; 元芳,我失恋了,你怎么看; 元芳,我314表白了,你怎...

  • 元芳,你怎么看Redux?

    生活不止眼前的苟且,还有诗和远方,远方除了远一无所有。-------反正不是我 刚接触react,发现还要学red...

  • “元芳,你怎么看”

    “元芳,你怎么看?” 最近流行一句电视剧台词,就是宰相狄仁杰常问贴身保镖李元芳的那句:“元芳,你怎么看?” 别看这...

  • 经常学习到底好不好?

    “有人说学习就是洗脑,元芳,你怎么看” 其实元芳怎么看并不重要,重要的是你收获了什么? 我经...

  • 谁的玻璃心

    没有产出 没有价值 元芳你怎么看

  • 御物师说059:泰国手绘动物杯垫

    我觉得是孩子画的,元芳,你怎么看?

  • 简书大侦探系列(1)谁是凶手?

    合理想象,注意细节,名侦探就是你。@@ 元芳,你怎么看?

  • 2018-11-24

    对于喝吾壶养生的问题-元芳你怎么看 元芳,最近我家乡出了喝吾壶,专用陈醋壶,还能养生 你怎么不看 回禀狄公,元芳看...

  • 元芳,你怎么看?支付宝提现明天开始收费了

    支付宝提现明天开始收费 元芳 你怎么看 然并卵 我没钱 号外、号外 张靓颖妈妈又爆料冯轲有小三 元芳 你怎么看 这...

  • 元芳的观点为啥这么重要?

    元芳,此事你怎么看? 2012年,有一句话风靡网络:元芳,此事你怎么看?一时间将近半数的网友争相跟风模仿,形成了“...

网友评论

    本文标题:元芳,你怎么看Redux?

    本文链接:https://www.haomeiwen.com/subject/yqbjsttx.html