Mobx / React 更新问题
Mobx / React update issue
我刚刚开始学习 Mobx,我正试图让这个组件更新,但没有成功。 似乎 应该更新,但实际上没有。我错过了什么?
'use strict';
const observer = mobxReact.observer;
const makeAutoObservable = mobx.makeAutoObservable;
const isObservable = mobx.isObservable;
const isObservableProp = mobx.isObservableProp;
const configure = mobx.configure;
configure({
// This gives you good warnings to read in the console
// enforceActions: "always",
computedRequiresReaction: true,
reactionRequiresObservable: true,
observableRequiresReaction: true,
disableErrorBoundaries: true
});
const HeadingBug = observer(function ({heading}) {
return React.createElement("span", null, "This is the heading bug. Current value: ", heading);
});
let heading = makeAutoObservable({
value: 100
});
ReactDOM.render(React.createElement(HeadingBug, {
heading: heading.value
}), document.getElementById('root'));
setTimeout(() => {
console.log(`isObservable: ${isObservable(heading)}`);
console.log(`isObservableProp: ${isObservableProp(heading, 'value')}`);
console.log('Changing Heading to 200');
heading.value = 200;
}, 2000);
您在此处取消引用 heading.value
为时过早:
ReactDOM.render(React.createElement(HeadingBug, {
heading: heading.value
}), document.getElementById('root'));
您基本上是在观察者组件中传递原始数值,而不是可观察值。
要修复它,只需将整个标题 object 作为 prop 传递,并在标题组件中使用值,如下所示:
const HeadingBug = observer(function ({heading}) {
return React.createElement("span", null, "This is the heading bug. Current value: ", heading.value);
});
我刚刚开始学习 Mobx,我正试图让这个组件更新,但没有成功。 似乎 应该更新,但实际上没有。我错过了什么?
'use strict';
const observer = mobxReact.observer;
const makeAutoObservable = mobx.makeAutoObservable;
const isObservable = mobx.isObservable;
const isObservableProp = mobx.isObservableProp;
const configure = mobx.configure;
configure({
// This gives you good warnings to read in the console
// enforceActions: "always",
computedRequiresReaction: true,
reactionRequiresObservable: true,
observableRequiresReaction: true,
disableErrorBoundaries: true
});
const HeadingBug = observer(function ({heading}) {
return React.createElement("span", null, "This is the heading bug. Current value: ", heading);
});
let heading = makeAutoObservable({
value: 100
});
ReactDOM.render(React.createElement(HeadingBug, {
heading: heading.value
}), document.getElementById('root'));
setTimeout(() => {
console.log(`isObservable: ${isObservable(heading)}`);
console.log(`isObservableProp: ${isObservableProp(heading, 'value')}`);
console.log('Changing Heading to 200');
heading.value = 200;
}, 2000);
您在此处取消引用 heading.value
为时过早:
ReactDOM.render(React.createElement(HeadingBug, {
heading: heading.value
}), document.getElementById('root'));
您基本上是在观察者组件中传递原始数值,而不是可观察值。
要修复它,只需将整个标题 object 作为 prop 传递,并在标题组件中使用值,如下所示:
const HeadingBug = observer(function ({heading}) {
return React.createElement("span", null, "This is the heading bug. Current value: ", heading.value);
});