【问题标题】:mapStateToProps must return an object. Instead received Map {}?mapStateToProps 必须返回一个对象。而是收到了 Map {}?
【发布时间】:2016-06-22 07:37:13
【问题描述】:

您好,我使用不可变映射作为状态,当我尝试使用 maspStateToProps 时出现此错误。

未捕获的不变违规:mapStateToProps 必须返回一个对象。 而是收到了 Map {}。

这是我的代码:

组件:

    const mapStateToProps = (state) => {
      return state
    }

     class LoanCalculator extends React.Component{

      componentWillMount(){
       this.dispatch(loadConstraints());
     }

      render(){
        return (
          <div>
            <h1> Loan Calculator </h1>
            <SlidersBox {...this.props}/>
         </div>
       )
     }
   }

    LoanCalculator = connect(
      mapStateToProps
    )(LoanCalculator)

   export default LoanCalculator

减速器

    import { Map } from 'immutable'
    import {LOAD_CONSTRAINTS, SET_AMOUNT_VALUE, SET_TERM_VALUE} from "../actions/actions";

    const initialState = new Map();

    export default function calculator(state = initialState, action){
      switch (action.type){
        case LOAD_CONSTRAINTS:
          return  state.set("constraints", action.constraints)
         case SET_AMOUNT_VALUE:
           return state.set("selectedAmount", action.amount)
        case SET_TERM_VALUE:
         return state.set("selectedTerm", action.term)
        default:
          return state
      }
    }

【问题讨论】:

  • 您的状态似乎是来自 immutable.js 的地图,而 mapStateToProps 应该返回一个对象,正如您的错误消息所述。尝试通过转换映射或将所需的值提取到对象结构中来返回对象。
  • 为什么不只是return {state}

标签: reactjs redux immutable.js react-redux


【解决方案1】:

这个 github 问题涵盖了这个确切的问题:https://github.com/reactjs/react-redux/issues/60

您可以在 mapStateToProps 函数中手动从地图中提取所需的值:

const mapStateToProps = (state) => {
  return {
       constraints: state.get('constraints'),
       selectedAmount: state.get('selectedAmount'),
       selectedTerm: state.get('selectedTerm'),
  };
}

【讨论】:

  • 非常感谢,这正是我所需要的。
  • 顺便说一句,这也迫使您牢记您要传递的确切内容。在某些时候,很明显您需要拆分一个不断增长的组件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2019-02-14
  • 2018-04-27
  • 1970-01-01
  • 2019-08-27
  • 2017-05-02
  • 1970-01-01
相关资源
最近更新 更多