简体   繁体   English

如何将组件道具保持在redux状态?

[英]How to persist the component props in redux state?

My redux state seems like this. 我的redux状态看起来像这样。

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. TrendingUpIcon用于呈现特定页面。

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. 但是TrendingUpIcon不是可序列化的值,刷新时它不再存在。

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: 在上述情况下,您的redux数据可能如下所示:

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. 您需要找到一种使您的类型可序列化的方法。

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

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