使用mobx在渲染中实现内联函数

问题描述 投票:0回答:1

我可以在mobx中使用bind函数进行渲染吗?我知道这种做法会导致性能下降,但我的同事说,如果我们使用mobx,我们可以在渲染中执行bind函数

例:

import { inject, observer } from 'mobx-react'

@inject('store')
@observer
export default class Component extends React.Component {
  render() {
    const {
      store: {
        pushByPath,
      },
    } = this.props
    return (
      <div>
        <button
          onClick={() => pushByPath('param1')}
        />
        <button
          onClick={() => pushByPath('param2')}
        />
        <button
          onClick={() => pushByPath('param3')}
        />
      </div>
    )
  }
}
reactjs mobx mobx-react
1个回答
0
投票

如果你需要将你的函数pushByPath绑定到商店的实例,你可以遵循这样的模式:

import {action} from 'mobx';

class Store {

   @action.bound pushByPath(path) {
       // this here will always point to an instance of Store
   }
}

实际上,你可以使用bind并且真正重新创建功能是一个性能命中,但对于现代浏览器来说真的非常小。你是否使用mobx并不重要。

© www.soinside.com 2019 - 2024. All rights reserved.