react+mobx 编写 withStoreHistory 装饰器

向Store注入History对象
本文介绍了一种在React应用中向store注入history对象的方法,通过withStoreHistory高阶组件实现,便于store内部函数调用history进行页面跳转。示例展示了如何结合inject和observer装饰器使用此方法。

主要作用是向store里面注入一个history对象,方便story里面的函数调用

function withStoreHistory(storeName) {
  if (!storeName) return console.error(`必须输入一个查询数据的store`);
  return function(Target) {
    class WithStoreHistory extends Component {
      componentDidMount() {
        const { history } = this.props;
        const store = this.props[storeName];
        store.history = history;
      }
      render() {
        return <Target {...this.props} />;
      }
    }
    return WithStoreHistory;
  };
}

使用

需要在inject调用后才能获取到store的数据,所以写在inject下面

const MERCHANTSTORE = "merchantStore";

@inject(MERCHANTSTORE)
@withStoreHistory(MERCHANTSTORE)
@observer
class BusinessEntrance extends Component {
  render() {
    return (
      <div>...</div>
    );
  }
}

函数中使用

  @action.bound
  handleSettingData() {
    this.history.push("/merchants_settled");
  }

转载于:https://www.cnblogs.com/ajanuw/p/10090243.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值