把redux添加到项目的步骤
index.js 部分
- 创建
store
跟reducer
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);
- 用
包起整个
App
const App = () => (
);
-
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 部分
import { connect } from 'react-redux';
- connect component
export default connect(mapStateToProps)(Counter);
- 加入
mapStateToProps
// Add this function:
function mapStateToProps(state) {
return {
count: state.count
};
}
- 加入
dispatch
,emit action
increment = () => {
// fill in later
console.log("increment");
this.props.dispatch({type:'INCREMENT'});
}
-
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 学习笔记】请检查
- 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;
}
-
mapStateToProps
有没有指定要绑定的props?
function mapStateToProps(state) {
return {
count: state.count,
campaignData: state.campaignData
};
}