首页 > 解决方案 > 类型错误:state.getIn 不是函数

问题描述

我在我的 react 项目中实现不可变,将它与 redux 一起使用,使用 fromJS() 函数(来自不可变库)使状态成为不可变对象。在我的 reducer 文件中,一切正常,我收到一个动作,我可以使用 setIn() 函数设置新值,我可以使用 getIn() 函数访问状态。

但是,当我使用 mapStateToProps 从 connect() 函数获取状态时,即使 console.log 显示一个明显不可变的对象,我也不能在这里使用不可变函数,例如 toJs() 或 getIn()。我总是收到这个错误:TypeError: state.getIn is not a function

我的 index.js 文件

import React from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import { template as templateAction } from './actions';
import withReducer from '../../../reducer/withReducer';
import templateReducer from './reducer';

export const Template = ({ name, template }) => (
  <Button onClick={template}>
    {name}
  </Button>
);

Template.propTypes = {
  name: PropTypes.string.isRequired,
  template: PropTypes.func.isRequired,
};

export const mapStateToProps = (state) => {
  console.log('state is equal to', state);
  return (
    {
      name: state.getIn(['templateReducer', 'name']),
    });
};

export const mapDispatchToProps = (dispatch) => ({
  template: () => dispatch(templateAction()),
});

export default compose(
  withReducer('templateReducer', templateReducer),
  connect(mapStateToProps, mapDispatchToProps),
)(Template);

console.log(state) 的结果

console.log(state) 的结果

PS:当我不使用不可变状态时,一切正常。

标签: reactjsreduxreact-reduximmutable.js

解决方案


看起来state内部mapStateToProps函数是一个对象,它的一个属性为 'templateReducer',其值为 type Map

我对我的 React 知识有点生疏,但也许分享代码templateReducer会有所帮助。

减速器功能有什么withReducer('templateReducer', templateReducer)作用?

似乎它templateReducer在将其发送到mapStateToProps函数之前将状态从减速器设置为键。(也许??)

可能,在使用不可变方法之前更改此函数以访问状态将消除错误。

export const mapStateToProps = (state) => {
  console.log('state is equal to', state);
  return (
    {
      name: state['templateReducer']?.getIn(['name']),
    });
};

推荐阅读