简体   繁体   English

我如何确保React道具的类型正确

[英]How can I ensure React props are of the correct type

I have a component that deals with fairly large datasets, and I've created a Proxy wrapper around array that helps deal with repeated operations, like sort. 我有一个处理相当大的数据集的组件,并且围绕数组创建了一个代理包装器,该包装器有助于处理重复操作(例如排序)。

I want to ensure that if data (the data prop) is passed into my component as an array, it gets the proxy wrapped round it. 我想确保如果数据( data属性)以数组的形式传递到我的组件中,那么它将得到环绕它的代理。 In other words, something like this: 换句话说,是这样的:

constructor(props, ...args) {
  if (props.data && !props.data.isData) {
    props.data = new Proxy(props.data, proxyHandlers);
  }

  super(props, ...args);
}

(and something similar in componentWillReceiveProps). (以及componentWillReceiveProps中类似的内容)。

This doesn't work, because React locks props to make it immutable. 这是行不通的,因为React会锁定道具以使其不可变。 What's the correct, React-y way of accomplishing this? 什么是实现此目标的正确的React-y方法?

You should use a higher order component to transform the props into what you want. 您应该使用更高阶的组件将道具转换为所需的道具。

Something like 就像是

const props => {
  if (props.data && !props.data.isData) {
    const newData = new Proxy(props.data, proxyHandlers);
    return <MyOldComponent data={newData} />;
  }
  return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM