在react中使用redux入门。
基本的例子使用redux管理react的状态。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdn.bootcss.com/redux/4.0.1/redux.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
const initialState = {
cart: [
{
product: 'bread 700g',
quantity: 2,
unitCost: 90
},
{
product: 'milk 500ml',
quantity: 1,
unitCost: 47
}
]
}
const ADD_TO_CART = 'ADD_TO_CART'
const renducer = function (state=initialState, action) {
switch (action.type) {
case ADD_TO_CART:
return {
...state,
cart:[...state.cart, action.payload],
}
default:
return state;
break;
}
}
const store = Redux.createStore(renducer)
//class声明组件
class ClassComponent extends React.Component {
addToCart(product, quantity, unitCost){
store.dispatch({
type:ADD_TO_CART,
payload:{
product, quantity, unitCost
}
})
}
render(){
return (
<div>
<h1>{this.props.v1}--{store.getState().cart.length}</h1>
<button onClick={()=>{this.addToCart('coffee1',1,100)}}>addToCart1</button>
<button onClick={()=>{this.addToCart('coffee2',2,200)}}>addToCart2</button>
</div>
)
}
}
const render = ()=>{
ReactDOM.render(
<div>
<ClassComponent v1={'hello redux'} />
<button onClick={()=>{console.log(store.getState())}}>getState</button>
</div>,
document.getElementById('example')
);
}
render()
let unsubscribe = store.subscribe(() =>{
render();
console.log(store.getState());
});
//解除监听
// unsubscribe();
</script>
</body>
</html>
参考文档:
Redux 入门教程
Redux入门教程(快速上手)
高阶函数connect
接受四个参数:
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
mapStateToProps
允许我们将store中的数据作为props绑定到组件上。
const mapStateToProps = (state) => {
return {
count: state.count
}
}
mapDispatchToProps
将action作为props绑定到组件上。
const mapDispatchToProps = (dispatch, ownProps) => {
return {
increase: (...args) => dispatch(actions.increase(...args)),
decrease: (...args) => dispatch(actions.decrease(...args))
}
}
mergeProps
不管是stateProps还是dispatchProps,都需要和ownProps merge 之后才会被赋给MyComp。connect的第三个参数就是用来做这件事。通常情况下,你可以不传这个参数,connect就会使用Object.assign替代该方法。
[mergeProps(stateProps, dispatchProps, ownProps): props]
options
基本上也会用到