【问题标题】:React Native Redux : "Undefined is not an object (evaluating 'action.type')"React Native Redux:“未定义不是对象(评估'action.type')”
【发布时间】:2019-02-09 14:33:18
【问题描述】:

我正在使用 Redux 和 ReactNative,我想用 reducer 创建一个商店

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

undefined 不是对象(正在评估 '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)

这里是我使用“dispatch”的地方:

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)

有人有想法吗??

【问题讨论】:

    标签: javascript reactjs react-native redux react-redux


    【解决方案1】:

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

    export default toggleFavorite;
    

    它会起作用的

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多