代码之家  ›  专栏  ›  技术社区  ›  R. Kohlisch

访问容器中的reducer返回未定义

  •  0
  • R. Kohlisch  · 技术社区  · 6 年前

    我只是想在我的React应用程序中集成一个新的容器,用Redux连接它,并希望看到一切正常工作。但事实并非如此。通过访问减速器 this.props.selection 给我 undefined .我不知道为什么。它可以在其他容器中工作,并且减速器有一些定义良好的初始状态。-我不确定这里有什么区别?我错过了什么小事吗?

    import React, { Component } from 'react'
    import { connect } from 'react-redux';
    import {bindActionCreators} from 'redux';
    
    export class AudioPlayer extends Component {
      constructor(props) {
        super(props);
        this.state = { someComponentState : true }
      }
    
      onLog() {
        console.log("Logging:");
        console.log(this.props.selection); // gives me: undefined
      }
      render() {    
        return (
          <div>
               <button onClick={()=> this.onLog()}>LOG</button>
          </div>
        )
      }
    }
    
    function mapStateToProps (state) {
      return {
        selection: state.selection
      };
    }
    
    export default connect(mapStateToProps)(AudioPlayer);
    

    PS:我已经对这个组件进行了一些简化,但我认为它仍然应该反映出问题所在。

    编辑:减速器示例 但是,有人要求查看Reducer,我尝试了使用几个Reducer,这些Reducer已经在应用程序中实现,并在其他容器中工作,所以我认为这不是问题所在,但谁知道呢:

    import { SELECT_ITEM } from '../actions/types';
    
    export default function(state = {}, action) {
      switch(action.type) {
        case SELECT_ITEM: 
          return {...state, error:'', selected: true};
      }
    
      return state;
    }
    

    edit2:似乎根本没有调用mapstatetoprops 我刚刚尝试在mapstatetoprops中做一个console.log,看看它是否被调用,似乎从来没有被调用过。没有任何记录。为什么会这样?

    function mapStateToProps (state) {
        console.log("In map function");
        console.log(state);
    
      return {
        selection: state.selection, //both return
        auth: state.auth            // undefined
      };
    }
    

    我还添加了另一个reducer(auth),它在应用程序的其他地方工作,但这里返回未定义。

    edit3:我的根减速器

    import { combineReducers } from 'redux';
    import { reducer as form } from 'redux-form';
    
    //reducer imports
    import authReducer from './auth_reducer';
    import articlesReducer from './articles_reducer';
    import userReducer from './user_reducer';
    import currentSelectionReducer from './currentSelection_reducer';
    
    const rootReducer = combineReducers({
      auth: authReducer,
      user: userReducer,
      articles: articlesReducer,
      selection: currentSelectionReducer,
    });
    
    export default rootReducer;
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Rakesh Makluri    6 年前

    可以尝试从“导出类音频播放器扩展组件”中删除“导出”吗?

    您还可以检查: mapStateToProps not getting called at all

        2
  •  1
  •   Felix K.    6 年前

    组件代码正常。

    你的减速器应该是

    export default function(state = { selected: false }, action) {
    

    进一步阅读:

        3
  •  1
  •   Sophie Cooperman    6 年前

    1)调试时请检查 输入准确的案例 在Reducer中,它理解action.type==select_项,并返回新状态。

    2)还要注意,选择是一个对象,其中包含“选定”的内容。 你的 选择 '还原程序包含:…状态,错误:'', 挑选出来的 真的}

    也许这有点困惑?