【发布时间】: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