【问题标题】:Redux state not updatingRedux 状态未更新
【发布时间】:2016-08-22 10:32:49
【问题描述】:

我的 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

所以在最后一步,状态不会更新。关于为什么的任何想法? 谢谢!

【问题讨论】:

    标签: reactjs firebase redux firebase-realtime-database


    【解决方案1】:

    我认为您在更改商店时使用了错误的功能。由于您使用的是seamless-immutable,因此set 函数期望作为参数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

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 2018-08-04
      • 2018-06-29
      • 1970-01-01
      • 2021-02-20
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多