redux实例
Posted FAN
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redux实例相关的知识,希望对你有一定的参考价值。
使用的是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实例的主要内容,如果未能解决你的问题,请参考以下文章