【问题标题】:Mobx-state-tree doesn't rerender on a new Map referenceMobx-state-tree 不会在新的 Map 引用上重新渲染
【发布时间】:2019-07-27 11:14:48
【问题描述】:

对于 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>
  }
}

【问题讨论】:

    标签: reactjs mobx mobx-react mobx-state-tree


    【解决方案1】:

    你的 treeStore 应该是 @observable

    class App extends Component {
      @observable treeStore;
    }
    

    【讨论】:

      【解决方案2】:

      types.map 不是您的常规 Map虽然它有类似的方法),虽然期望它可以接受 Map 是合乎逻辑的,但显然它不会(也许你应该在他们的tracker 上提出一个问题)。但是,要解决您眼前的问题,只需在您的 setTree 操作中传递一个对象,或者 - 数组数组:

      this.treeStore.setTree({ 'one': '1' });
      

      this.treeStore.setTree([[ 'one', '1' ]]);
      

      【讨论】:

      • 在我的实际示例中,我不能使用对象,因为我的 Map 有“非字符串”键。所以不幸的是,这对我来说不是一个真正的选择。谢谢你的答案。
      • 你可以使用数组数组。我提到了它,现在用一个例子更新了我的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 2021-02-25
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多