2016-08-22 170 views
2

我的reducer不會更新我的Redux狀態樹,我還沒找到解決方案,所以我希望得到一些幫助。這是我的代碼:Redux狀態不更新

減速

import Immutable from 'seamless-immutable' 
import { loadFirebaseData } from '../actions/firebaseActions' 

const FETCH_FIREBASE_DATA = 'FETCH_FIREBASE_DATA' 

const initialState = Immutable({}) 

export default function firebaseReducer(state = initialState, action) { 
    switch (action.type) { 
    case FETCH_FIREBASE_DATA: 
    return state 
    .set('firebaseData', fetchData(action)) 
    } 
    return state 
} 


function fetchData(action) { 
    return { 
    firebaseData: action.firebaseData 
    } 
} 

應用

class App extends Component { 

    componentWillMount() { 
    this.props.fetchFirebaseData('gallery') 
    } 

function mapStateToProps(state) { 
    console.log('state',state.firebaseReducer) 
    return { 
    galleryItems: state.firebaseReducer 
    } 
} 

function mapDispatchToProps(dispatch) { 
    return bindActionCreators(firebaseActions, dispatch) 
} 

export default connect(mapStateToProps, mapDispatchToProps)(App) 

如果我是註銷減速的執行:

import Immutable from 'seamless-immutable' 
import { loadFirebaseData } from '../actions/firebaseActions' 

const FETCH_FIREBASE_DATA = 'FETCH_FIREBASE_DATA' 

const initialState = Immutable({}) 

export default function firebaseReducer(state = initialState, action) { 

    console.log(1) 
    switch (action.type) { 

    case FETCH_FIREBASE_DATA: 
    console.log(2) 
    return state 
    .set('firebaseData', fetchData(action)) 
    } 

    console.log(3) 
    console.log('state', state) 
    return state 
} 


function fetchData(action) { 
    return { 
    firebaseData: action.firebaseData 
    } 
} 

的控制檯顯示:

1 
3 
state: Object {__immutable_invariants_hold: true} 
1 
3 
Object {__immutable_invariants_hold: true} 
Object {__immutable_invariants_hold: true} 
1 
2 

因此,在最後一步,狀態不會更新。任何想法爲什麼? 謝謝!

回答

0

我認爲你使用錯誤的功能來改變你的商店。由於您正在使用seamless-immutableset函數期望作爲參數2個字符串:鍵和值。在你的代碼中,你傳遞給它一個字符串和一個對象。

根據seamless-immutable documentation設置state.firebaseDataaction.firebaseData使用合併功能與對象爲傳遞價值:

export default function firebaseReducer(state = initialState, action) { 
    switch (action.type) { 
    case FETCH_FIREBASE_DATA: 
     return state 
     .merge(fetchData(action)) 
    } 
    return state 
} 

其他的問題,我與你提供的例子中看到的是,在mapStateToPros功能,您正在訪問的成員firebaseReducer無處可尋的狀態。你打算把它映射到state.firebaseData嗎?