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

一、本案例在 理解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页面代码:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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 (
            
type="button" onClick={()=>getData()} value="点击获取数据"/>
    { data.data ? data.data.map((item, index) => (
  • {item.name}
  • )) : null }
) } } 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:[email protected]
 * @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(
    
        

使用react-redux和fetch请求数据

, rootEl);

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

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

你可能感兴趣的:(React,redux)