mobx-state-tree 很新。每当更改我的模型以使 types.map 获得新引用时,我的组件都不会重新呈现。在我的示例中,更改模型上的字符串确实会触发重新渲染。我正在阅读我希望重新渲染的组件中的这两个属性,并用@observer
.
这是一个 Stackblitz 示例:https ://stackblitz.com/edit/react-n54mud
在第 37 行注释以使其工作。
模型:
export const treeModel = types
.model({
tree: types.map(types.string),
test: ''
})
.actions(self => ({
setTree(tree) {
self.tree = tree
},
setTest(data) {
self.test = data;
}
}));
应用程序
class App extends Component {
treeStore;
constructor() {
super();
this.state = {
name: 'React'
};
this.treeStore = treeModel.create();
this.treeStore.setTree(new Map());
setTimeout(() => {
this.treeStore.setTree(new Map());
// Enabling this will retrigger the rendering of the Test comp
//this.treeStore.setTest('azerty');
}, 2000);
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
<Test store={this.treeStore}></Test>
</div>
);
}
}
测试组件
@observer
class Test extends Component {
constructor(props) {
super(props);
}
render() {
console.log('rendered');
const {tree, test} = this.props.store;
return <div>test</div>
}
}