有什么方法console.log可以让 a 在 mobx@observable改变值时自动触发吗?
我会使用 mobx 开发工具来完成此操作,但它会触发大量控制台日志,因此很难确定我正在跟踪其值的属性。
我正在使用 mobx/react 构建两个小部件,其中所有逻辑都位于商店内。两者共享大部分设计规则,因此他们的商店 95% 相同。有聪明的方法来处理这种情况吗?例如,是否可以创建这样的继承?
class Animal {
@observable name = "";
constructor(name) {
this.name = name;
}
@computed get sentence() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
@observable isBarking = false;
@computed get bark() {
if (this.isBarking){
console.log('The dog is barking');
}
}
@action
setIsBarking(isBarking) {
this.isBarking = isBarking;
}
}
Run Code Online (Sandbox Code Playgroud) 我收到了来自 Mobx 的警告信息。
[mobx.array] 尝试读取超出范围 (0) 的数组索引 (0)。请先检查长度。MobX 不会跟踪越界索引
@observable checks = {
deviceType: ['phone','laptop', ...],
deviceTypeChecks: [],
...
}
@action
selectAllChecks = (target, type) => {
const targetChecks = []
if (this.checks[target].length !== this.checks[type].length) {
this.checks[target].forEach(el => targetChecks.push(el))
}
this.checks[type] = targetChecks
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能删除那个警告?但是,这段代码没有问题。它运作良好。
我正在selectAllChecks通过 onChange 函数使用函数。
const {
deviceType,
deviceTypeChecks
} = this.props.store.checks
<label className="mr10">
<input
type="checkbox"
checked={deviceType.length === deviceTypeChecks.length}
onChange={() =>
selectAllChecks('deviceType', 'deviceTypeChecks')
}
/>
<span>All device type</span>
</label>
Run Code Online (Sandbox Code Playgroud)
我必须为 IE 提供 4 个版本。
"mobx": …Run Code Online (Sandbox Code Playgroud) 更新数组时,我无法让 MobX 渲染。这是代码的简化版本:
import React, { useState } from 'react'
import { flow, makeObservable, observable } from 'mobx'
import { observer } from 'mobx-react'
import { ResourceList } from './ResourceList'
import { ResourceItem } from './ResourceItem'
export const View = observer(() => {
const [{
items,
}] = useState<MyState>(new MyState())
return <ResourceList items={items} />
})
export class MyState {
constructor() {
makeObservable(this)
this._fetch()
}
@observable public items: ResourceItem[] = []
private _fetch = flow(function* (this: MyState) {
const items = …Run Code Online (Sandbox Code Playgroud) 我定义了一个 mobx 地图如下:
@observable editors = observable.map();
Run Code Online (Sandbox Code Playgroud)
然后我在editors下面添加了对象:
editors.set(key, {
alias: 'alias-1',
message: 'hello',
})
Run Code Online (Sandbox Code Playgroud)
当我从editor下面获取对象时:
let myEditor = editors.get(key)
Run Code Online (Sandbox Code Playgroud)
返回的对象myEditor具有一些内置函数,例如:
$mobx:ObservableObjectAdministration
get alias:function ()
set alias:function ()
get message:function ()
set message:function ()
Run Code Online (Sandbox Code Playgroud)
我想知道如何从editor?
假设以下结构
stores/
RouterStore.js
UserStore.js
index.js
Run Code Online (Sandbox Code Playgroud)
每个...Store.js文件都是一个包含@observable和的 mobx 存储类@action。index.js只导出所有商店,所以
import router from "./RouterStore";
import user from "./UserStore";
export default {
user,
router
};
Run Code Online (Sandbox Code Playgroud)
访问另一家商店的正确方法是什么?即在我的 UserStore 中,当用户身份验证更改时,我需要从 RouterStore 分派操作。
我累了import store from "./index"里面UserStore,然后用store.router.transitionTo("/dashboard")(transitionTo)是RouterStore的类内的动作。
但这似乎不能正常工作。
我是 Mobx 的新手,但到目前为止它运行良好,而且我已经取得了很大进展。我有一个带有 mobx 和 mobx-persist 的 react-native 应用程序。我正在使用 axios 从 Wordpress 站点中提取帖子。我试图改进的功能是“添加到收藏夹”功能。
这是我的 PostsStore:
export default class PostsStore {
// Define observables and persisting elements
@observable isLoading = true;
@persist('list') @observable posts = [];
@persist('list') @observable favorites = [];
// Get posts from Wordpress REST API
@action getPosts() {
this.isLoading = true;
axios({
url: 'SITE_URL',
method: 'get'
})
.then((response) => {
this.posts = response.data
this.isLoading = false
})
.catch(error => console.log(error))
}
// Add post to favorites list, ensuring …Run Code Online (Sandbox Code Playgroud) 这在 React 中是小菜一碟。如果您希望 MobX 存储在任何 React 组件中可用,您只需使用 mobx-react@inject组件即可。就像是:
import React from 'react';
import {inject} from 'mobx-react';
@inject('myStore')
class Dummy extends React.Component {
Run Code Online (Sandbox Code Playgroud)
然后,我的商店可以作为道具使用:
this.props.myStore.myMethod();
不错,很方便……并且仅限 React。也许我错过了一些东西,但我找不到从普通 ES6 类访问我的商店的方法。如何在纯 Vanilla Javascript 的普通 ES6 类中获得相同的结果?
我正在尝试克隆引用另一个模型的模型,但我得到:Error: [mobx-state-tree] Failed to resolve reference 'H1qH2j20z' to type 'AnonymousModel' (from node: /usualCustomer)...在克隆中。原版解决没问题。
这是我的模型:
const Job = types.model({
id: types.optional(types.identifier(types.string), shortid.generate()),
jobNumber: types.optional(types.string, ''),
description: '',
usualCustomer: types.maybe(types.reference(Customer)),
})
const Customer = types.model({
id: types.optional(types.identifier(types.string), shortid.generate()),
name: types.optional(types.string, 'New customer'),
})
Run Code Online (Sandbox Code Playgroud)
这个函数说明了问题:
editJob = job => {
console.log('Original', job)
var newClone = clone(job)
console.log('Clone', newClone)
}
Run Code Online (Sandbox Code Playgroud) 我在 React 应用程序中使用带有 Typescript 的 mobx-state-tree。而且,我在使用 Typescript 时遇到了问题,它抱怨 mobx type 的类型types.safeReference。看起来safeReference模型定义中的类型与您.create()实际创建模型实例时使用的类型不同。在我的代码中,selectedProduct的类型被转换为string | number | undefined | nullin productStore,但在模型定义中是IStateTreeNode<...> | undefined | null,这就是我在我的根存储中收到错误的原因。我该如何解决?
这是我的产品商店:
import { types } from "mobx-state-tree";
const Product = types.model("Product", {
id: types.identifier,
name: types.string
})
const ProductStore = types
.model("ProductStore", {
products: types.array(Product),
selectedProduct: types.safeReference(Product),
})
.actions((self) => ({
// actions here
}));
export const productStore = ProductStore.create({
products: [],
selectedProduct: undefined // …Run Code Online (Sandbox Code Playgroud) mobx ×10
mobx-react ×6
javascript ×4
reactjs ×4
typescript ×2
observable ×1
react-native ×1
state ×1