React-Redux链接React与Redux开发项目

11 篇文章 0 订阅

一、本案例在 理解redux和redux的中间件redux-thunk的认识基础上及结合fetch如果有不清楚的可以查看下-fetch下一代ajax请求数据的封装用户在页面上点击按钮触发事件调用数据

二、项目结构

|react-redux-demo
|----webpack.config.js
|----package.json
|----index.html
|----node_modules  //存放工具包
|----src  
|--------actions
|------------index.js
|--------components
|------------ShowData.js
|--------containers
|------------ShowDataConnect.js
|--------reducers
|------------getJson.js
|------------index.js
|--------utils
|------------fetch.js

三、各文件代码

3.1 webpack.config.js文件代码:
/**
 * @author:水痕
 * @time:2017-02-25 17:27
 * @email:332904234@qq.com
 * @version:1.0
 * @fileName:webpack.config
 * @title:
 */
'use strict';
module.exports = {
    entry:{
        index:'./src/index.js',
    },
    output:{
        path:__dirname,
        filename:'[name].build.js',
    },
    module:{
        loaders:[
            {
                test:/\.(js|jsx)$/,
                exclude:'/node_modules/',
                loader:'babel-loader',
                query:{
                    presets:['es2015','react']
                }
            }
        ]
    },
    resolve:{
        extensions:['.js',".css",".jsx"]
    }
}
3.2 package.json代码如下:
{
  "name": "react-demo05",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --inline --host localhost --port 3000"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^6.3.2",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.23.0",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-redux": "^5.0.3",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  }
}
3.3 index.html页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="root"></div>
</body>
<script type="text/javascript" src="index.build.js"></script>
</html>
3.4 src/action/index.js代码
/**
 * @author:水痕
 * @time:2017-03-29 14:13
 * @email:332904234@qq.com
 * @version:1.0
 * @fileName:index
 * @direction:
 * @title:
 */
'use strict';
export const GETJSON = 'GETJSON';
import {getJson} from './../utils/fetch.js';

export function getData() {
    return (dispatch, getState) => {
        //由于是本人之前公司的,不方便直接公布
        getJson('http://www.xxx.com/xxxx.php?c=Product&a=category', function (data) {
            dispatch({type: GETJSON, dataSet: data});
        })
    }
}

3.5 src/components/ShowData.js代码如下:

/**
 * @author:水痕
 * @time:2017-03-29 14:28
 * @email:332904234@qq.com
 * @version:1.0
 * @fileName:ShowData
 * @direction:
 * @title:
 */
'use strict';
import React, {Component,PropTypes} from "react";

export default class ShowData extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        let {getData, data} = this.props;
        return (
            <div>
                <input type="button" onClick={()=>getData()} value="点击获取数据"/>
                <ul>
                    {
                        data.data ? data.data.map((item, index) => (
                                <li key={`list-${index}`} data-id={`list-${item.id}`}>{item.name}</li>
                            )) : null
                    }
                </ul>
            </div>
        )
    }
}
ShowData.propTypes = {
    getData: PropTypes.func.isRequired,
}


3.6 src/containers/ShowDataConnect.js代码如下:
/**
 * @author:水痕
 * @time:2017-03-29 14:35
 * @email:332904234@qq.com
 * @version:1.0
 * @fileName:ShowDataConnect
 * @direction:
 * @title:
 */
'use strict';
import ShowData from '../components/ShowData';
import {connect} from 'react-redux';
import * as ActionCreators from '../actions';

export default connect(
    function (state) {
        /**
         * 个人建议先查看下state是什么,然后再操作,
         * 这里函数的返回值是到展示组件中的
         */
        console.log('state', state);
        return {
            data: state.getJson,
        }
    },
    ActionCreators
)(ShowData);
3.7 src/reducers/getJson.js代码:
/**
 * @author:水痕
 * @time:2017-03-29 08:43
 * @email:332904234@qq.com
 * @version:1.0
 * @fileName:getJson
 * @direction:
 * @title:
 */
'use strict';
import { GETJSON } from '../actions';
/**
 * 初始化数据,也可以是空的
 * @type {{data: [*], errmsg: string, errno: string}}
 */
let initState = {
    data:[
        {id:1,name:'张三'}
    ],
    errmsg:'',
    errno:''
}
export default function getJson(state = initState, action) {
    switch (action.type) {
        case GETJSON:
            /**
             * 个人尝试过不能直接使用
             * return Object.assign(initState,action.dataSet);
             */
            return Object.assign({},initState,action.dataSet);
        default:
            return state;
    }
}
3.8 src/reducers/index.js代码:
/**
 * @author:水痕
 * @time:2017-03-29 14:39
 * @email:332904234@qq.com
 * @version:1.0
 * @fileName:index
 * @direction:
 * @title:
 */
'use strict';
import { combineReducers } from 'redux';
import getJson from './getJson';
/**
 * 虽然本例中只有一个reducer,但还是使用了`combineReducers`来进行合并,便于后期的拓展。
 */

const rootReducer = combineReducers({
    getJson
});

export default rootReducer;
3.9 src/utils/fetch.js
/**
 * @author:水痕
 * @time:2017-03-29 14:13
 * @email:332904234@qq.com
 * @version:1.0
 * @fileName:fetch
 * @direction:
 * @title:利用fetch封装获取数据的方法
 */
'use strict';

export function getJson(url,callback){
    fetch(url).then((response) => response.json())
        .then((data)=>{
            callback(data)
        })
}
4.0 src/index.js代码:
/**
 * @author:水痕
 * @time:2017-03-29 08:21
 * @email:332904234@qq.com
 * @version:1.0
 * @fileName:index
 * @direction:
 * @title:
 */
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
import counter from './reducers';
import ShowDataConnect from './containers/ShowDataConnect';
const store = createStore(counter, applyMiddleware(thunk));
const rootEl = document.getElementById('root');

ReactDOM.render(
    <Provider store={store}>
        <div>
            <h2>使用react-redux和fetch请求数据</h2>
            <ShowDataConnect />
        </div>
    </Provider>, rootEl);

四、运行项目在黑窗口中输入npm run start

说明:本人也是在研究react生态圈,欢迎有一起研究技术的朋友加我,我们一起研究,一起讨论技术难点,直接加我QQ:332904234

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值