reactjs - 类型错误: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) 的结果
PS:当我不使用不可变状态时,一切正常。
解决方案
看起来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']),
});
};
推荐阅读
- ios - 如何让 UIStackView 完美填充?
- javascript - 我将如何将一些新值插入特定集合?
- javascript - 如何将 JavaScript 代码添加到 Laravel for BackPack?
- javascript - 为什么拼接项在下一个列表条目时返回显示?
- regex - nginx中的正则表达式前瞻问题
- python - 导致问题的两个版本的 Pandas
- r - 为什么过滤到 ggplot() 中的数据集样本会返回不正确的样本?
- docker - 从 docker 容器访问外部端口
- spring - 如何在 `AuthenticationKeyGenerator` 中添加标头?
- angular - 在定义 NgModule 时使用外部 JSON 文件的值