FlatList Mobx ReactNative缺少计算的选项:get

问题描述 投票:0回答:1

当我单击添加项目按钮时,我看到添加了项目的日志,但视图没有重新呈现。

我的商店:

import {observable, action, computed} from 'mobx';

export default class ObservableItemStore {
  @observable items = ["Item A", "Item B"];

  @computed get myItems() {
    return this.items;
  }

  @action addItem(item)) {
    console.log("Adding to" + this.items);
    this.items.push(item);
  }
}
import React, {Component} from 'react';
import {Button, FlatList, StyleSheet, Text, View} from 'react-native';
import { observer } from 'mobx-react';
import { Observer } from 'mobx-react/native';
import { Items } from '../../stores';
interface Props {}

@observer
class List extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Button
          title="Add Item"
          onPress={() => {
            Items.addItem("Foo");
          }}
        />
        <Observer>{() => {
          return <FlatList
            data={ Items.items }
            renderItem={({item}) => <Text>{item}</Text>}
          />
        }}
        </Observer>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

export default List;

为什么视图不能重新渲染?

react-native mobx react-native-flatlist mobx-react
1个回答
0
投票

您应该在render(items.slice(),items.map(),items.length等)中使用一个数组属性。

https://mobx.js.org/best/react.html#incorrect-use-an-observable-but-without-accessing-any-of-its-properties

© www.soinside.com 2019 - 2024. All rights reserved.