简体   繁体   中英

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. 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).

This doesn't work, because React locks props to make it immutable. What's the correct, React-y way of accomplishing this?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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