本文介绍了mapStateToProps 必须返回一个对象.而是收到 Map {}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的代码:

组件:

 const mapStateToProps = (state) =>{返回状态}类 LoanCalculator 扩展了 React.Component{componentWillMount(){this.dispatch(loadConstraints());}使成为(){返回 (<div><h1>贷款计算器</h1><SliderBox {...this.props}/>

)}}贷款计算器 = 连接(映射状态到道具)(贷款计算器)导出默认贷款计算器

减速器

 import { Map } from 'immutable'从../actions/actions"导入 {LOAD_CONSTRAINTS, SET_AMOUNT_VALUE, SET_TERM_VALUE};const initialState = new Map();导出默认函数计算器(state = initialState, action){开关(动作.类型){案例 LOAD_CONSTRAINTS:返回 state.set("constraints", action.constraints)案例 SET_AMOUNT_VALUE:返回 state.set("selectedAmount", action.amount)案例 SET_TERM_VALUE:返回 state.set("selectedTerm", action.term)默认:返回状态}}
解决方案

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

您可以在 mapStateToProps 函数中手动从 Map 中提取您想要的值:

const mapStateToProps = (state) =>{返回 {约束:state.get('constraints'),selectedAmount: state.get('selectedAmount'),selectedTerm: state.get('selectedTerm'),};}

Hello i use Immuteble Map for state and when i try maspStateToProps i have this error.

Here is my code:

Component:

    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

REDUCER

    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
      }
    }
解决方案

This github issue covers this exact problem: https://github.com/reactjs/react-redux/issues/60.

You can manually extract the values you want from your Map in your mapStateToProps function:

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

这篇关于mapStateToProps 必须返回一个对象.而是收到 Map {}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 23:56