确保数组的每个元素符合React中的自定义形状(再次)

时间:2018-02-14 15:48:17

标签: javascript reactjs react-proptypes

我试图过去的错误是:Warning: Failed prop type: checker is not a function

我和这里发布的问题非常相似: Ensuring each element of an array property conforms to custom shape in React

Here is the object I'm trying to validate

我尝试添加的对象很复杂,我无法弄清楚正确的语法。

以下是我尝试的内容:

Card.propTypes = {
  node: shape({
    images: PropTypes.arrayOf(PropTypes.objectOf(PropTypes.shape({
      entity: PropTypes.shape({
        image: PropTypes.shape({
          derivative: PropTypes.shape({
            url: PropTypes.string,
          }),
        }),
      }),
      mid: PropTypes.number,
    }))),
    title: PropTypes.string,
    body: {
      value: PropTypes.string,
    },
  }).isRequired,
  ctaHandler: PropTypes.func.isRequired,
  deleteHandler: PropTypes.func.isRequired,
};

似乎这个问题也很相似 - 数字作为键。 React PropTypes - shape with numbers as keys

还试过这个:

Card.propTypes = {
  node: PropTypes.shape({
    author: PropTypes.string,
    body: {
      value: PropTypes.string,
    },
    images: PropTypes.arrayOf(PropTypes.shape({
      entity: PropTypes.shape({
        image: PropTypes.shape({
          derivative: PropTypes.shape({
            url: PropTypes.string,
          }),
        }),
      }),
      mid: PropTypes.number,
    })),
    nid: PropTypes.number,
    title: PropTypes.string,
    uuid: PropTypes.string,
  }).isRequired,
  ctaHandler: PropTypes.func.isRequired,
  deleteHandler: PropTypes.func.isRequired,
};

我还尝试将从GraphQL服务器返回的模型对象映射到一些不那么复杂的东西。

  let nodes = result.nodes.entities.map(node => { 
    const newNode = {...node};
    newNode.images = newNode.images.map(image => {
      return {url: image.entity.image.derivative.url, mid: image.mid};
    })
    return newNode;
  });
  this.setState({
    nodes: nodes
  });

应该给我以下签名:

Card.propTypes = {
  node: PropTypes.shape({
    author: PropTypes.shape({
      name: PropTypes.string,
    }),
    body: {
      value: PropTypes.string,
    },
    images: PropTypes.arrayOf(PropTypes.shape({
      url: PropTypes.string,
      mid: PropTypes.number,
    })),
    nid: PropTypes.number,
    title: PropTypes.string,
    uuid: PropTypes.string,
  }).isRequired,
  ctaHandler: PropTypes.func.isRequired,
  deleteHandler: PropTypes.func.isRequired,
};

不幸的是,我仍然遇到同样的错误: Failed prop type: checker is not a function in Card

1 个答案:

答案 0 :(得分:0)

如果您有<div class="wrap"> <div class="one">Hi</div> <div class="two">my second div</div> </div>,那么您的Warning: Failed prop type: checker is not a function声明中可能会出现拼写错误。这就是为什么它在这种情况下显示,你有:

propTypes

应该是

body: {
    value: PropTypes.string,
},