将数组作为道具传递,将prop-types定义为数组,但它表示我传递了一个对象

问题描述 投票:0回答:2

我正在尝试访问我的reducer数组并将其映射为props。它工作正常,但当我尝试使用ESLint标准化我的代码时,我需要定义我的prop类型,所以我做了它,作为一个数组。

然后我收到一个错误说:Warning: Failed prop type: Invalid prop 'articles_list' of type 'array' supplied to 'Content', expected 'object'

我搜索它,发现人们遇到路由器问题,建议尝试路由器测试版...但它在ESLint之前有用。我看不出有什么问题......我甚至怀疑我的英语理解哈哈..将道具类型转换为对象,但任何工作都有效。

在我的组件中

const mapStateToProps = state => ({
  articles_list: state.articles_list,
});

class Content extends Component {
  ...
}

Content.propTypes = {
  articles_list: PropTypes.shape([]),
};
Content.defaultProps = {
  articles_list: [],
};

在我的减速机中

const initialState = {
  articles_list: [],
}

export const reducer = (state = initialState, action) => {
  switch (action.type) {
    case GET_ALL_ARTICLES_PAGE:
      return {
        ...state,
        articles_list: [...state.articles_list, action.payload],
      };
      [...]
  }
}
reactjs react-proptypes
2个回答
1
投票

PropTypes.shape返回一个具有特定形状的object

尝试以下:

 Content.propTypes = {
      articles_list: PropTypes.arrayOf(PropTypes.shape(*your object shape*)),
    };

如果您的数组是数组数组尝试:

   Content.propTypes = {
          articles_list: PropTypes.arrayOf(PropTypes.number),
        };

0
投票

你试过这个吗?

Content.propTypes = {
  articles_list: PropTypes.array,
};

或者,如果要定义数组的形状,可以使用此方法

Content.propTypes = {
  articles_list: PropTypes.arrayOf(
    PropTypes.shape({
      code: PropTypes.string,
      id: PropTypes.number,
    })
  ),
};

阅读有关所有可用propTypes here的文档。

© www.soinside.com 2019 - 2024. All rights reserved.