我使用Redux将数据保存在全局状态,该状态根据用户的操作进行更新。当用户单击按钮时,应该更新状态,并将当前状态显示在按钮上。相反,初始保持显示没有变化。我在下面列出了我的组件和减速器。
主要组成部分:
import React, { Component, PropTypes } from 'react';
import Picture from '../../components/picture.jsx';
import ShoppingCart from '../../components/shoppingcart.jsx';
import { browserHistory } from 'react-router';
import { createStore } from 'redux';
import cart from '../../reducers/index.js';
var flag = false;
const store = createStore(cart);
export default class Products extends Component {
constructor(props) {
super(props);
this.state = {clothingData: 0}
}
componentWillMount() {
fetch('/t')
.then((result) => {
return result.json();
})
.then((re) => {
flag = true;
this.setState({ clothingData: re });
})
.catch(function(error){
console.log(error);
});
}
componentDidMount(){
fetch('/ship')
.then((result) => {
return result.json();
})
.then((res) => {
console.log(res);
})
.catch(function(error){
console.log(error);
});
}
render(){
if (!flag){
return (
<div>
</div>
);
}
else{
//console.log(this.state.clothingData[0].path);
//console.log(this.state.clothingData[0].fileName);
//console.log(this.state.clothingData);
return (
<div>
<Picture src = {this.state.clothingData} onClick = { () => {browserHistory.push('/Product'); }} name = {"joe"} />
<ShoppingCart value={ store.getState() } onIncrement={() => store.dispatch({ type: 'INCREMENT' })} />
</div>
);
}
}
}
购物车组件:
import React, { Component, PropTypes } from 'react';
export default class ShoppingCart extends Component {
render(){
const { onIncrement } = this.props
return(
<div>
<button onClick = {onIncrement}> {this.props.value} </button>
</div>
);
}
}
减速机:
export default (state = 2, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
答案 0 :(得分:1)
框中的redux与任何库(如Angular,或React,...等)无关。您必须手动将redux绑定到您的应用程序。
以下是将redux绑定到反应的说明。
答案 1 :(得分:1)