2017-02-20 48 views
0

我使用Redux將數據保存在全局狀態,該狀態基於用戶的操作進行更新。當用戶點擊一個按鈕時,它應該更新狀態,並將當前狀態顯示在按鈕上。相反,最初的遺蹟顯示不變。我已經列出了我的組件和reducer。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 
    } 
} 

回答

1

由於您使用的終極版,你有沒有考慮使用的react-redux綁定反應整合呢?

通過商店觸發行爲不被認爲是最佳做法,如您在此comment中所見。

查看Provider組件。