码迷,mamicode.com
首页 > 其他好文 > 详细

redux实例

时间:2017-12-07 22:44:42      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:xtend   doc   create   roo   creat   nbsp   amp   res   gets   

使用的是create-react-app脚手架

src/index.js

import React from ‘react‘
import ReactDOM from ‘react-dom‘
import App from ‘./App‘
import {createStore, combineReducers} from ‘redux‘;

// step1: 创建reducers
const reducers = combineReducers({
    films: function(state=[], action) {
        let {type, payload} = action;
        switch(type) {
            case "GET_FILM_DATA":
                var newS = [...state];
                newS = payload;
                return newS;
            default:
                return state;
        }
    }
})

// step:2 创建store
const store = createStore(reducers, {});

// 把store传递给组件
function renderPage() {
    ReactDOM.render(<App store={store} />, document.getElementById(‘root‘));
}
renderPage();

// step3: 注册回调
store.subscribe(renderPage)

src/App.js

import React, { Component } from ‘react‘;
import axios from ‘axios‘;

class App extends Component {
    componentDidMount() {
            var that = this;
            axios.get("/v4/api/film/now-playing?__t=1512647107236&page=1&count=5")
            .then(function(res){
                console.log(res);
                that.props.store.dispatch({
                    type: "GET_FILM_DATA",
                    payload: res.data.data.films
                })
            })
        }
        render() {
            var films = this.props.store.getState().films;
            return (
                <div>
                    <ul>
                        {
                            films.map((item, index)=>{
                                return <li key={item.id}>
                                    <h2>{item.name}</h2>
                                    <img src={item.cover.origin} />
                                </li>;
                            })
                        }
                    </ul>
                </div>
            )
        }
       }

export default App;

package.json增加

"proxy": {
    "/v4": {
      "target": "https://m.maizuo.com",
      "changeOrigin": true,
      "pathRewrite": {
        "^/v4": "/v4"
      },
      "ws": true
    }
  }

 

:

 

redux实例

标签:xtend   doc   create   roo   creat   nbsp   amp   res   gets   

原文地址:http://www.cnblogs.com/fanlinqiang/p/8001292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!