Redux状态不更新

时间:2016-08-22 10:32:49

标签: reactjs firebase redux firebase-realtime-database

我的reducer不会更新我的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)

如果我要注销reducer的执行:

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

所以在最后一步,状态没有得到更新。有什么想法吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您使用了错误的功能来更改商店。由于您使用seamless-immutableset函数期望作为参数2字符串:键和值。在你的代码中,你传递给它字符串和一个对象。

根据seamless-immutable documentationstate.firebaseData设置为action.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