我有一个组件并注入了一个商店实例:
import React from "react";
import { inject, observer } from "mobx-react";
import Retention from "./Retention";
@inject(() => {
return {
retentionStore: new Retention()
};
})
@observer
export default class RetentionChart extends React.Component {
constructor(props) {
super(props);
}
componentWillReceiveProps() {
const { setFlag } = this.props.retentionStore;
setFlag(Math.random());
}
render() {
const { retentionStore } = this.props;
const { loading, error, result } = retentionStore;
console.log(loading, error, result);
return null;
}
}
这是Retention
商店代码:
import { observable, autorun, reaction, action, computed, flow } from "mobx";
import axios from "axios";
export default class Retention {
@observable error = "";
@observable loading = false;
@observable result = null;
@observable flag = false;
@action
setFlag = value => {
this.flag = value;
};
query = flow(function*() {
this.loading = true;
this.error = "";
try {
this.result = yield axios
.get("https://randomuser.me/api/")
.then(response => {
return response.data;
});
} catch (error) {}
this.loading = false;
});
constructor() {
reaction(
() => this.flag,
() => {
this.query();
}
);
}
}
我想要做的很简单:当组件的任何道具更改时,它都会查询一次
但是,当我将组件放入父组件中时,尝试更新子组件的属性,查询可以吃午饭,但是子组件对商店中可观察到的更改没有响应:
import React from "react";
import { observer, inject } from "mobx-react";
import RetentionChart from "../RetentionChart";
export default class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {
flag: false
};
}
render() {
const { flag } = this.state;
return (
<div
onClick={() =>
this.setState({
flag: !this.state.flag
})
}
>
<p>Clickable</p>
<RetentionChart flag={flag} />
</div>
);
}
}
我的代码有什么问题?为什么无法响应?我该如何解决?
答案 0 :(得分:0)
@inject(() => {
return {
retentionStore: new Retention()
};
})
每次您都有新商店。尝试以下代码。
const retentionStore = new Retention();
@inject(() => ({retentionStore}))