简体   繁体   中英

How to persist the component props in redux state?

My redux state seems like this.

import SearchIcon from "@material-ui/icons/Search";

const initState = {
  salesIconList: {
    Icon: TrendingUpIcon,
    color: "#ff9800",
    text: "sale analysis",
    onClick: "/sales/sales"
  }
};

The TrendingUpIcon is used for rendering specific page.

class SalesIconList extends React.Component {
  handleRoute = route => {
    this.props.history.push(route);
  };

  render() {
    children.push(
      <ButtonType
        key={v4()}
        Icon={stockIconList.Icon}
        color={stockIconList.color}
        text={stockIconList.text}
        onClick={this.handleRoute.bind(this, stockIconList.onClick)}
      />
    );
    return (
      {children}
    );
  }
}

But the TrendingUpIcon is not a serializable value, when refreshing it is no longer exist.

For this sort of issue, you can create a lookup hash that makes your type serialisable. For example:

import TrendingIcon from 'whevever'

const iconHash = {
  trendingIcon: TrendingIcon
}

export iconHash

Then whenever you need an icon, you store a string representation, and look it up. For example:

import iconHash from 'wheverer'

...
<ButtonType
  key={v4()}
  Icon={iconHash[stockIconList[i].Icon]}
  color={stockIconList[i].color}
  text={stockIconList[i].text}
  onClick={this.handleRoute.bind(this, stockIconList[i].onClick)}
/>

In the case above, your redux data might look like:

const initState = {
  salesIconList: {
    Icon: 'trendingIcon', // notice it is now a string
    color: "#ff9800",
    text: "sale analysis",
    onClick: "/sales/sales"
  }
}  

This is a crude example, but hopefully you get the general idea. You need to make a way to make your types serialisable.

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