用最简单的方式,了解react全家桶之redux
本文以create-react-app项目作为开端,从最基础代码成长为一个实际项目的过程。
redux组成部分createStore.js 1.我们来说说第一个,createStore.js 先看看代码 import { createStore } from 'redux' import reducer from ‘./reducer’ export default () => { let store = createStore(reducer) return store } 是不是炒鸡简单? 2.接着,我们看看我们的reducer是干什么的,看代码 function counter(state = {value : 0},action) { switch (action.type) { case 'INCREASE': return Object.assign({},state,{ value: state.value + 1 }) case 'DECREASE': return Object.assign({},{ value: state.value - 1 }) default: return state } } export default counter 是不是也炒鸡简单,无非就是修改一个state的value参数!这个state是带默认值。 那我们要怎么触发修改呢? 没错,那就是发起action。 3.action.js到底干了些什么? import { bindActionCreators } from 'redux' export const INCREASE = 'INCREASE' export const increase = () => ({ type: INCREASE}) export const DECREASE = 'DECREASE' export const decrease = () => ({ type: DECREASE}) export const containerActions = dispatch => bindActionCreators({ increase,decrease },dispatch) bindActionCreators: 是由redux提供的辅助函数 好了好了,到此,我们就把一个完整的redux流程写完了。 App.js import React,{ Component } from 'react'; import logo from './logo.svg'; import './App.css'; import { connect } from 'react-redux' import { containerActions } from './action' class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started,edit <code>src/App.js</code> and save to reload. </p> <button onClick={ this.props.increase }>INCREASE</button><br/> <button onClick={ this.props.decrease }>DECREASE</button><br/> <p>VALUE: {this.props.value}</p> </div> ); } } const mapStateToProps = (state) => { return { value: state.value } } //connect是由react-redux提供的辅助函数,作用是将store state里的值,映射到this.props //containerActions是把action里的方法绑定到当前组件,也就是App的this.props export default connect(mapStateToProps,containerActions)(App); index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { Provider } from 'react-redux' import createStore from './createStore' let store = createStore() //通过Provider把store传递到react ReactDOM.render( <Provider store={store}> <App /> </Provider>,document.getElementById('root')); registerServiceWorker(); 完美运行。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |