Im Reduxを使用してデータをグローバル状態に保持します。これは、ユーザーの操作に基づいて更新されます。ユーザーがボタンをクリックすると、状態が更新され、現在の状態がボタンに表示されます。代わりに、初期値は変更なしで表示されたままです。私は以下のコンポーネントとレデューサーをリストアップしました。ReduxストアがReactを使用して更新されない
メインコンポーネント:
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
}
}