3
rated 0 times
[
6]
[
3]
/ answers: 1 / hits: 25776
/ 8 Years ago, thu, february 25, 2016, 12:00:00
I use the following pattern in several components throughout my app. I notice that many people discourage using forceUpdate(), and some even call it a hack. So how should this be done without using it?
// user.js
export default class User extends EventEmitter {
constructor(args) {
super();
this.id = args.id;
this.isActivated = args.isActivated || false;
}
activate() {
this.isActivated = true;
this.emit('change');
}
}
// UserView.jsx
export default class UserView extends React.Component {
componentDidMount() {
this.props.user.on('change', this.onUserUpdate);
}
onUserUpdate() {
this.forceUpdate();
}
render (
var user = this.props.user;
return (
<div>
<span>User {user.isActivated ? 'is' : 'is not'} activated.</span>
<button onClick={user.activate()}>Activate</button>
</div>
);
);
}
// app.js
var user = new User({ id: 123 });
ReactDOM.render(<UserView user={user} />, container);
More From » reactjs