Redux|Redux 学习笔记

把redux添加到项目的步骤
index.js 部分

  1. 创建storereducer
import { createStore } from 'redux'; import { Provider } from 'react-redux'; const initialState = {count: 0 }; function reducer(state=initialState, action) { switch(action.type){ case 'INCREMENT': return Object.assign({}, state, { count: state.count + 1 }); case 'DECREMENT': return Object.assign({}, state, { count: state.count - 1 }); default: return state; } return state; } const store = createStore(reducer);

  1. 包起整个App
const App = () => ( );

  1. index.js例子
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Counter from './App'; import registerServiceWorker from './registerServiceWorker'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; const initialState = {count: 0 }; function reducer(state=initialState, action) { switch(action.type){ case 'INCREMENT': return Object.assign({}, state, { count: state.count + 1 }); case 'DECREMENT': return Object.assign({}, state, { count: state.count - 1 }); default: return state; } return state; } const store = createStore(reducer); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); registerServiceWorker();

app.js 部分
  1. import { connect } from 'react-redux';
  2. connect component
export default connect(mapStateToProps)(Counter);

  1. 加入mapStateToProps
// Add this function: function mapStateToProps(state) { return { count: state.count }; }

  1. 加入dispatch,emit action
increment = () => { // fill in later console.log("increment"); this.props.dispatch({type:'INCREMENT'}); }

  1. app.js例子
import React from 'react'; import { connect } from 'react-redux'; class Counter extends React.Component { increment = () => { // fill in later console.log("increment"); this.props.dispatch({type:'INCREMENT'}); }decrement = () => { // fill in later console.log("decrement"); this.props.dispatch({type:'DECREMENT'}); }render() { return (Counter {this.props.count} ) } }// Add this function: function mapStateToProps(state) { return { count: state.count }; }export default connect(mapStateToProps)(Counter);

疑难排解
如果mapStateToProps没有成功 【Redux|Redux 学习笔记】请检查
  1. reducer 返回的结果对不对
function reducer(state=initialState, action) { console.log(action,"reducer got action"); switch(action.type){ case 'UPDATE_DATA': //正确示范 return Object.assign({}, state, { data: action.data }); case 'INCREMENT': //错误示范, 这种返回会覆盖state.data return { count: state.count + 1 }; default: return state; } return state; }

  1. mapStateToProps 有没有指定要绑定的props?
function mapStateToProps(state) { return { count: state.count, campaignData: state.campaignData }; }

    推荐阅读