继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

元芳,你怎么看Redux?

MMTTMM
关注TA
已关注
手记 303
粉丝 65
获赞 364

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

<br />

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

网上盗张图


700

Paste_Image.png

<br />

700

redux.gif

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

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

700

Paste_Image.png

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

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

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

import React , { Component } from 'react';//这是Actionimport { 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对象//刷新的actionCreateexport const refreshData = () => {    return {        type: REFRESHDATA
    }
}  
//成功的actionCreateexport 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 。 看如下截图

700

Paste_Image.png

我们看reducer 代码

// reducers/count.jsimport { 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.jsimport { combineReducers } from 'redux' // 利用    combineReducers 合并reducersimport { 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



作者:二月长河
链接:https://www.jianshu.com/p/2357039e3b5f


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP