【问题标题】:Given action "X", reducer "Y" returned undefined给定动作“X”,reducer“Y”返回未定义
【发布时间】:2019-10-08 19:01:52
【问题描述】:

我对 React 中的 Redux 有疑问。输入此主题的标题后,我一直在查看一些相关的问题,但我无法为我的案例找到相同问题的答案。

我有以下文件:

Index.JS

import snackbarContentReducer from '../src/shared/redux/reducers/snackbar-reducer';
import shoppingCartReducer from '../src/shared/redux/reducers/shopping-cart-reducer';
import userReducer from '../src/shared/redux/reducers/user-reducer';

const store = createStore(
    combineReducers(
        {
            //user: userReducer,
            //shopping_cart: shoppingCartReducer,
            snackbar_content: snackbarContentReducer
        }
    )
    ,window.devToolsExtension && window.devToolsExtension());


ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));

用户和购物车还没有实现,动作和减速器还没有任何代码。

App.JS

import { connect } from 'react-redux';
import { setSnackbarContent } from '../src/shared/redux/actions/snackbar-actions';

class App extends Component {

  render() {
    return (
      <BrowserRouter>
          <div>
            { console.log(this.props.snackbar_content) }
            { this.props.setSnackbarContent('nieuw') }

            //Cleared my routes here 

          </div>
      </BrowserRouter>
    );
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(App);

function mapStateToProps(state){
  return {
    snackbar_content: state.snackbar_content
  }
}

function mapDispatchToProps(dispatch){
  return {
      setSnackbarContent : (text) => {
        dispatch(setSnackbarContent(text));
      }
  }
}

我可以从商店获取道具(因为它们从状态映射到道具)。但我无法更改商店中的snackbar_content。我得到的错误如下:

错误:给定动作“SET_SNACKBAR_CONTENT”,reducer “snackbar_content” 返回未定义。要忽略一个动作,你必须明确地返回 之前的状态。如果你希望这个减速器没有价值,你可以 返回 null 而不是 undefined。

这是由以下行引起的:

dispatch(setSnackbarContent(text));

snackbar-action.JS

export const SET_SNACKBAR_CONTENT = 'SET_SNACKBAR_CONTENT';

export function setSnackbarContent(text){
    return { 
        type: SET_SNACKBAR_CONTENT, 
        payload: text
    }
}

snackbar-reducer.JS

import { SET_SNACKBAR_CONTENT } from '../actions/snackbar-actions';

export default function snackbarContentReducer(state = 'init snackbar', action){

    if(action.type === SET_SNACKBAR_CONTENT){
        return action.payload.snackbar_content;
    }

    return state;
}

为什么会出现这个错误,我该如何解决?

提前致谢。

PS:我是 Redux 的新手,我使用了官方文档和一些 YouTube 视频作为参考。

【问题讨论】:

  • 你的减速器返回snackbar_content,这将是未定义的。该操作使用payload

标签: javascript reactjs redux


【解决方案1】:

您似乎在您的操作负载中寻找snackbar_content,但您从未设置它,而是将负载设置为您期望的任何状态。

换句话说,在你的 reducer 中,只返回 payload 作为状态

if(action.type === SET_SNACKBAR_CONTENT){
    return action.payload;
}

【讨论】:

    【解决方案2】:

    你(和我)忘记在 reducer 中为 switch 语句添加 default 案例。

    default:
       return state;
    

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2016-05-05
      • 2017-05-31
      • 2019-07-09
      • 2017-10-18
      • 2021-06-29
      相关资源
      最近更新 更多