先引入redux的插件:
在命令提示框中输入:
npm install redux@4.0.1
//或者
npm install react-redux@4.0.1 --save-dev
实现购物车的加减,需要的三个文件:
1.redux.js
import React from 'react';
import ReactDOM from 'react-dom' ;
//模拟商品购物车的内容
var cars={ps:[
{id:1,names:'香瓜',n:1},
{id:2,names:'西瓜',n:1},
{id:3,names:'番茄',n:1}
]}
//reducer
export function counter(state=cars,action){
switch(action.type){
case '加':
state.ps[action.ids].n+=1;
return state;
case '减':
state.ps[action.ids].n-=1;
return state;
default:
return state;
}
}
//action
export function Add(i){
return {type:'加',ids:i}
}
export function Del(i){
return {type:'减',ids:i}
}
2.index.js
import _ from 'lodash';
import React from 'react';
import ReactDOM from 'react-dom' ;
import {createStore} from 'redux';//使用函数createStore创建store数据点
import {counter,Add,Del} from './compoments/redux.js'
import Car from './compoments/car.js';
const store = createStore(counter);
function render(){
ReactDOM.render(
<Car store = {store} add={Add} del={Del}/>,
document.getElementById('app')
);
}
render();
store.subscribe(render);//监听dom
3.car.js
import React from 'react';
import ReactDOM from 'react-dom' ;
export default class Car extends React.Component{
constructor() {
super()
}
render(){
const store=this.props.store
const add=this.props.add
const del=this.props.del
// console.log('测试'+add)
// console.log('测试'+del)
return (
<div>
{store.getState().ps.map((v,i)=>
<p key={v.names}>{/* key是唯一的值 */}
{v.names}
{"=>"}
<input type="button" value="+" onClick={() => store.dispatch(add(i))} />
{v.n}
<input type="button" value="-" onClick={() => store.dispatch(del(i))} />
</p>)}
</div>
)
}
}
实例图:
最终效果: