Reputation: 1246
I had a problem when I used observer function in react-mobx
.
My source code like following,
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>
)
}
}
This component will rerender when student
object is changed.
but I want to control when to re-render.
In short, I want to catch the point when this component re-render.
(It means student
component was changed)
It's similar shouldComponentUpdate.
so I thought I can control using shouldComponentUpdate. but it doesn't work.
so how can I control this?
The final result I want is I don't want to re-render when the student
component has certain parameter when it's re-render.
Upvotes: 1
Views: 1709
Reputation: 10219
To answer you question, there actually is one way of doing it (very hacky), by monkey patching the shouldComponentUpdate
method:
@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>
)
}
}
That said, this is usually an indication that you are thinking about your data in the wrong way. Ideally your components should just be a pure render function of the current state of the application.
class Test extends React.Component {
render(){
if (student.name === 'foo') {
return <div>Custom info</div>
}
return (
<div>{student.name}</div>
)
}
}
Upvotes: 2
Reputation: 615
MWeststrate, one of the devs on MobX said this in a 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
Why would you want to control re-renders, can't you postpone updating the student then or do all updates at once with the help off a runInAction
?
Upvotes: 0