繁体   English   中英

React Native Redux:“未定义不是对象(正在评估'action.type')”

[英]React Native Redux : “Undefined is not an object (evaluating 'action.type')”

我将Redux与ReactNative一起使用,我想用reducer创建一个商店

而且,我在下面遇到错误,指向favouriteReducer.js中函数toggleFavorite()中的“ switch(action.type)”行。 我找到了类似的话题,但是没有解决...

未定义不是对象(评估“ action.type”)

favoriteReducer.js:

const initialState = { favoriteQuotes: [] }

function toggleFavorite(state = initialState, action) {
  let nextState
  switch (action.type) {
    case 'TOGGLE_FAVORITE':
      const favoriteQuoteIndex = state.favoriteQuotes.findIndex(item => item.id === action.value.id)
      if (favoriteQuoteIndex !== -1) {
        // La citation est déjà dans les favoris, on la supprime de la liste
        nextState = {
          ...state,
          favoriteQuotes: state.favoriteQuotes.filter( (item, index) => index !== favoriteQuoteIndex)
        }
      }
      else {
        // La citation n'est pas dans les favoris, on l'ajoute à la liste
        nextState = {
          ...state,
          favoriteQuotes: [...state.favoriteQuotes, action.value]
        }
      }
      return nextState || state
  default:
    return state
  }
}

export default toggleFavorite()

configureStore.js:

import { createStore } from 'redux';
import toggleFavorite from './Reducers/favoriteReducer'

export default createStore(toggleFavorite)

这是我使用“调度”的地方:

import React from 'react'
...
import { connect } from 'react-redux'

class QuoteDetail extends React.Component {

...

  _toggleFavorite() {
    const action = { type: "TOGGLE_FAVORITE", value: this.state.quote }
    this.props.dispatch(action)
  }

...

<Button title="Favoris" onPress={() => this._toggleFavorite()}/>

...

const mapStateToProps = (state) => {
  return {
    favoriteQuotes: state.favoriteQuotes
  }
}
export default connect(mapStateToProps)(QuoteDetail)

任何人都有一个主意吗?

导出时无需调用该函数,这会导致您的情况下的错误,请将其更改为

export default toggleFavorite;

它会工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM