购物车加调接口需要的三个JS文件:car.js、index.js、redux.js
index.js:
import _ from 'lodash';
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';//使用函数createStore创建store数据点
import { counter, Add, Del, Addv,Addvd } from './compoments/redux.js'
import thunk from 'redux-thunk';
import Car from './compoments/car.js';
const store = createStore(counter, applyMiddleware(thunk));
function render(){
ReactDOM.render(
<Car store = {store} add={Add} del={Del} addv={Addv} addvd={Addvd}/>,
document.getElementById('app')
);
}
render();
store.subscribe(render);//监听dom
redux.js:
import React from 'react';
import ReactDOM from 'react-dom' ;
var cars={ps:[]}
//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;
case '买':
let news="{'id':"+action.buyvs.id_coach+",'names':'"+action.buyvs.name_coach+"','pirce':"+action.buyvs.type_coach+",'n':1}";
state.ps.push(eval("("+news+")"));
return state;
default:
return state;
}
}
//action
export function Add(i){
return {type:'加',ids:i}
}
export function Del(i){
return {type:'减',ids:i}
}
export function Addv(ads) {
return {type:'买',buyvs:ads}
}
export function Addvd(i) {
return dispatch=>{
setTimeout(()=>{
dispatch(Add(i));
},2000);
};
}
car.js:
import React from 'react';
export default class Car extends React.Component {
constructor() {
super()
this.state = { vsinfo: [], sum: [] }
}
componentDidMount() {
this.getTeacher()
}
getTeacher() {
let ts = fetch("http://www.qhdlink-student.top/student/coacha.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: "username=cty&userpwd=12345678&userclass=67&type=2"
});
ts.then(res => res.json()).then(json => {//第一次获取的是json对象,返回的是props对象,第二次提取的是值,
for (let i in json) {//for...of便利的是数组,而for..in便利的是对象。
this.state.vsinfo.push(json[i])
}
this.setState(this.state.vsinfo)
});
}
sum() {
let a = 0;
for (let i = 0; i < this.state.sum.length; i++) {
a = a + this.state.sum[i]
}
return (
<div>{a}</div>
)
}
render() {
const store = this.props.store
const add = this.props.add
const del = this.props.del
const addv = this.props.addv
const addvd = this.props.addvd
return (
<div>
{store.getState().ps.map((v, i) => {
return (
<div key={v.names}>{/* key是唯一的值 */}
{v.names}
<input type="button" value="+" onClick={() => {
store.dispatch(addvd(i));
this.state.sum.push(v.pirce)
}} />
{v.n}
<input type="button" value="-" onClick={() => {
store.dispatch(del(i))
this.state.sum.pop(v.pirce)
}} /><br />
共:{v.pirce * v.n}元
</div>
)
})}
<div>总价:
{this.sum()}
</div>
{this.state.vsinfo.map((v, i) =>
<div key={i}>
{v.name_coach}:
{v.type_coach}元<input type="button" name="buy" value="购买" onClick={() => {
store.dispatch(addv(v))
this.state.sum.push(Number(v.type_coach))
console.log(store.getState())
}} /></div>)}
</div>
)
}
}
最终实现效果图: