简体   繁体   中英

ReactJS export const and component from one module

I have two modules that I want to share a const array. One of these modules includes both the const array and a component, whilst the other module only includes a component.

This is what I have in module "A".

export const ORDER_COLUMNS = [
  { name: 'orderNumber', title: 'Order', width: '10%',  type: 'string' },
  { name: 'orderType', title: 'Type', width: '10%',  type: 'string' }
];

class OrderGridControl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        orderColumns: ORDER_COLUMNS
    };
  }
  ...

}

export default OrderGridControl;

And in module "B".

import {OrderGridControl, ORDER_COLUMNS} from 'component/order-grid-control';

class OrderQueryPage extends React.Component {
      constructor(props) {
    super(props);
    this.state = {
        orderColumns: ORDER_COLUMNS
    };
    console.info(this.state.orderColumns);
  }

  ...

  render() {
    return (
      <div>
        <PropertyGrid gridSetup={this.state.orderColumns} />
      </div>
    );
  }
}

When I run this I get the following error. invariant.js:39 Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'moduleB'.

However, the console.info(this.state.orderColumns) line logs all the column objects I expect.

Interestingly, if I copy the array into module "B" and assign the columns in the constructor exactly the same way it seems to work. It only seems to be an issue when I'm importing from the other module.

You've got it almost right-- you're exporting a default export ( OrderGridControl ) and a named export ( ORDER_COLUMNS ).

However, in B.js, you're trying to import two named exports.

Modify your import to look like this:

import OrderGridControl, { ORDER_COLUMNS } from 'component/order-grid-control';

The advantage of having a default export is that you don't have to match its name exactly when importing it, so you could do something like

import GridControl, { ORDER_COLUMNS } from 'component/order-grid-control';

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