React + Mobx:尝试更新商店时'this'为null [英] React + Mobx: 'this' is null when trying to update store
问题描述
Mobx&入门做出反应,使商店无法更新.单击按钮时出现错误,该按钮应更新'me'属性:
Just getting started with Mobx & React and having trouble getting the store to update. I get error when clicking the button, which should update the 'me' property:
Store.js:12 Uncaught TypeError: Cannot set property 'me' of null
我的商店:
import { observable } from 'mobx';
class Store {
@observable me;
constructor() {
this.me = 'test';
}
change_me(){
this.me = 'test 1';
console.log(this); // null???
}
}
const store = new Store();
export default store;
组件:
import React from "react";
import { observer } from 'mobx-react';
export default class Layout extends React.Component{
render(){
var store = this.props.store;
return(
<div>
<button onClick={store.change_me}>{store.me}</button>
</div>
)
}
}
我可能已经错过了该工作原理的一些基本部分,但无法弄清楚.
I've probably missed some fundamental part of how this works, but can't figure it out.
推荐答案
是,对this
为空的执行事件回调进行响应.因为您只给onClick
回调提供了change_me
方法,而不给store
作为上下文.
Yes react execute event callbacks with this
being null. Since you only give the onClick
callback the change_me
method and not the store
as context.
您必须自己设置this
上下文.您可以通过以下方式做到这一点
You have to set the this
context yourself. you can do this in the following ways
正如@Eduard所说,您可以将其转换为箭头功能. Arrow函数可确保this
上下文在函数正文中保持不变:
as @Eduard said you can warp it into an arrow function. the Arrow function makes sure the this
context stays the same in the function body:
<button onClick={() =>store.change_me()}>{store.me}</button>
您还可以使用绑定方法:
<button onClick={store.change_me.bind(store)}>{store.me}</button>
这基本上是一样的事情.
this does basically the same thing.
为什么它们是坏习惯?在每个render()
调用上,将重新创建这些方法.并可能导致不必要的重新渲染.
Why are they bad practises? on every render()
call, these methods are re-created. and can result in extra unnecessary re-renders.
mobx提供了一个action.bound
,它使用适当的this上下文包装了该函数:
mobx provides a action.bound
which wraps the function with the proper this context:
@mobx.action.bound
change_me(){
this.me = 'test 1';
}
或者,es6类定义允许您自己正确定义此上下文:
Alternatively es6 class definition allows you to define the this context properly yourself:
@mobx.action
change_me = () => {
this.me = 'test 1';
}
请参阅箭头功能.在幕后:而不是在Store
类的原型上定义函数/方法.该方法是在constructor
中创建的,因此this
上下文变量始终与该类的实例匹配.
See the arrow function. behind the scenes: instead of defining the function/method on the prototype of the Store
class. the method is created in the constructor
so that the this
context variable always matches the instance of the class.
这样:
var a = new Store(); // a.me = 'test'
var b = new Store(); // b.me = 'test'
a.change_me = b.change_me; // change_me function contains its own this context.
a.change_me(); // a.me = 'test' b.me = 'test 1'
这篇关于React + Mobx:尝试更新商店时'this'为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!