zoukankan      html  css  js  c++  java
  • 怎么看Redux?

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

    网上盗张图


     
     

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

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

     

    接上门课程(https://www.cnblogs.com/passkey/p/10671644.html
    来继续写

    既然是使用了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 。 看如下截图

     

    我们看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



    作者:二月长河
    链接:https://www.jianshu.com/p/2357039e3b5f
    来源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 相关阅读:
    mysql 触发器
    监听mac价格变动,降价了就通知。
    mysql 索引、约束
    mysql 三种insert插入语句
    idea 控制台中文乱码
    go 刷算法第三题——二叉树根节点到叶子节点和为指定值的路径
    mysql 排序序号sql+斐波那契统计
    go 刷算法第二题——最长回文子串
    常见排序算法-基数排序、计数排序
    常见排序算法-选择、冒泡排序
  • 原文地址:https://www.cnblogs.com/passkey/p/10668696.html
Copyright © 2011-2022 走看看