把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);
- 用
<Provider>
包起整个App
const App = () => (
<Provider store={store}>
<Counter/>
</Provider>
);
-
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 = () => ( <Provider store={store}><Counter/></Provider> );
ReactDOM.render(<App />, 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 (
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement}>-</button>
<span>{this.props.count}</span>
<button onClick={this.increment}>+</button>
</div>
</div>
)
}
}
// Add this function:
function mapStateToProps(state) {
return {
count: state.count
};
}
export default connect(mapStateToProps)(Counter);
疑难排解
如果mapStateToProps没有成功
请检查
- 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
};
}
网友评论