首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mobx-state-tree不会在新的地图引用上重新呈现

Mobx-state-tree不会在新的地图引用上重新呈现
EN

Stack Overflow用户
提问于 2019-07-27 19:14:49
回答 2查看 1.4K关注 0票数 0

对mobx-state-tree非常陌生。无论何时我的模型被更改,以便types.map获得新的引用,我的组件都不会被重新呈现。在我的示例中,更改模型上的字符串确实会触发重新呈现。我正在读取我希望重新呈现的组件中的这两个属性,并用@observer对其进行了装饰。

下面是Stackblitz的一个例子:https://stackblitz.com/edit/react-n54mud

在第37行添加注释以使其正常工作。

型号:

代码语言:javascript
复制
export const treeModel = types
    .model({
        tree: types.map(types.string),
    test: ''
    })
    .actions(self => ({
        setTree(tree) {
      self.tree = tree
    },
    setTest(data) {
      self.test = data;
    }
    }));

应用程序

代码语言:javascript
复制
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>
    );
  }
}

测试组件

代码语言:javascript
复制
@observer
class Test extends Component {

  constructor(props) {
    super(props);
  }

  render() {
      console.log('rendered');
      const {tree, test} = this.props.store;
      return <div>test</div>
  }
}
EN

回答 2

Stack Overflow用户

发布于 2019-09-11 19:09:20

您的treeStore应为@observable

代码语言:javascript
复制
class App extends Component {
  @observable treeStore;
}
票数 1
EN

Stack Overflow用户

发布于 2019-07-30 14:22:28

types.map不是普通的Map (尽管它有类似的方法),虽然期望它可以接受Map是合乎逻辑的,但显然它不能(也许你应该在他们的上提交一个关于它的问题)。然而,要解决眼前的问题,只需在setTree操作中传递一个对象,或数组的数组:

代码语言:javascript
复制
this.treeStore.setTree({ 'one': '1' });

代码语言:javascript
复制
this.treeStore.setTree([[ 'one', '1' ]]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57231566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档