我可以在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>
)
}
}
如果你需要将你的函数pushByPath
绑定到商店的实例,你可以遵循这样的模式:
import {action} from 'mobx';
class Store {
@action.bound pushByPath(path) {
// this here will always point to an instance of Store
}
}
实际上,你可以使用bind
并且真正重新创建功能是一个性能命中,但对于现代浏览器来说真的非常小。你是否使用mobx
并不重要。