我如何控制 mobx 观察者?

how can I control mobx observer?

我在 react-mobx.
中使用观察者函数时遇到问题 我的源代码如下,

import React from 'react';
import { observer } from 'mobx-react';

@observer
class Test extends React.Component{
  render(){
    const { student } = this.props; // it's @observable object

    return (
      <div>{student.name}</div>
    )
  }
}

此组件将在 student 对象更改时重新呈现。
但我想控制何时重新渲染。

简而言之,我想抓住这个组件重新渲染的重点。
(这意味着 student 组件已更改)
类似于 shouldComponentUpdate.
所以我想我可以控制使用 shouldComponentUpdate。但它不起作用。

那么我该如何控制呢?
我想要的最终结果是当 student 组件在重新渲染时具有特定参数时我不想重新渲染。

MWeststrate,MobX 的一位开发者在 post

There is no way to customize the tracking behavior. The whole idea is that you should not implement shouldComponentDidUpdate on your own. observer will only react to observables that are actually used in the last run of the render (so not to observables that are behind some if statement that returns falsy). Being able to customize this would allow you to break the basic guarantee of MobX: views are always in sync with state, and is not a desirable situation.

Link: https://github.com/mobxjs/mobx-react/issues/230

你为什么要控制重新渲染,你不能 postpone 更新学生然后在 runInAction 的帮助下一次完成所有更新吗?

为了回答你的问题,实际上有一种方法可以做到这一点(非常 hacky),通过猴子修补 shouldComponentUpdate 方法:

@observer
class Test extends React.Component {

  constructor(props) {
    super(props);
    this.mobxShouldComponentUpdate = this.shouldComponentUpdate;
    this.shouldComponentUpdate = this.customShouldComponentUpdate;
  }

  customShouldComponentUpdate = (props, ...args) => {
    if (props.student === 'foo') {
      return false;
    }
    return this.mobxShouldComponentUpdate(props, ...args);
  }

  render(){
    const { student } = this.props; // it's @observable object
    return (
      <div>{student.name}</div>
    )
  }
}

也就是说,这通常表明您以错误的方式考虑数据。理想情况下,您的组件应该只是应用程序当前状态的纯渲染函数。

class Test extends React.Component {
  render(){
    if (student.name === 'foo') {
      return <div>Custom info</div>
    }
    return (
      <div>{student.name}</div>
    )
  }
}