javascript - MobX 存储在 React Native 中未更新

标签 javascript reactjs react-native redux mobx

我在我的 React-Native 应用程序中实现了 MobX 存储,以跟踪用户是否被关注或取消关注。关注/取消关注正在注册,但 MobX 存储尚未更新。我尝试使用 this.follows.items[index] = { ...user, isFollowing: !user.isFollowing } 直接更新它,但由于某种原因,商店不会触发更新。

这是View组件

@observer
class FollowsListView extends Component<Props> {
  follows =
    this.props.followType === 'followers'
      ? followsStore.getFollowersListLoader(this.props.userId)
      : followsStore.getFollowingListLoader(this.props.userId);

  componentDidMount = () => {
    this.follows.lazyLoad();
  };

  render() {
    return (
      <>
        <AppHeader
          title={
            this.props.followType === 'followers' ? 'FOLLOWERS' : 'FOLLOWING'
          }
        />
        <FlatList
          contentContainerStyle={{ padding: 15 }}
          data={this.follows.items}
          keyExtractor={this.getId}
          onEndReached={this.follows.loadMore}
          onEndReachedThreshold={0.2}
          onRefresh={this.follows.loadFromStart}
          refreshing={this.follows.isLoading}
          renderItem={this.renderFollows}
        />
      </>
    );
  }

  private getId = (user: { id: string }) => user.id;

  renderUserActionButton(user: UserContainer) {
    console.log(user);
    return (
      user.id !== _SessionManager.id && (
        <TouchableOpacity
          onPress={() => this.openActionMenu(user.following || user.owner)}
        >
          <Image source={Images.moreDots} />
        </TouchableOpacity>
      )
    );
  }

  openActionMenu(user: User) {
    const name = user.name || user.username;

    const followOption = { name: 'follow', title: `Follow @${name}` };
    const unfollowOption = { name: 'unfollow', title: `Unfollow @${name}` };

    const options = {
      customButtons: [user.isFollowing ? unfollowOption : followOption],
      title: null,
      takePhotoButtonTitle: null,
      chooseFromLibraryButtonTitle: null,
    };

    ImagePicker.showImagePicker(options, ({ customButton }) => {
      if (customButton === 'follow') {
        this.props.changeIsFollowingUser(user.id, false);
      }
      if (customButton === 'unfollow') {
        this.props.changeIsFollowingUser(user.id, true);
      }

      const index = this.follows.items.findIndex((user) => user.id);
      this.follows.items[index] = { ...user, isFollowing: !user.isFollowing };
    });
  }

  private renderFollows: ListRenderItem<UserContainer> = ({ item: user }) => {
    const userId = user.following ? user.following.id : user.id;

    return (
      <UserRow
        actionContent={this.renderUserActionButton(user)}
        onPress={() => this.props.navigateTo('ProfilePublic', { userId })}
        user={user.following || user.owner}
      />
    );
  };
}

const mapDispatchToProps = (dispatch: Function): MappedDispatch =>
  bindActionCreators(
    {
      changeIsFollowingUser,
      navigateTo,
    },
    dispatch
  );

export default connect(
  null,
  mapDispatchToProps
)(FollowsListView);

这是关注商店

import ListLoader from 'Network/ListLoader';
import { Follows } from 'Follows/Types';
import _API from 'Network/API';

class FollowsStore {
  followers = new Map<string, Follows>();
  followersList = new Map<string, ListLoader<Follows>>();
  following = new Map<string, Follows>();
  followingList = new Map<string, ListLoader<Follows>>();

  getFollowersListLoader(userId: string) {
    const list = this.followersList.get(userId);
    if (list) return list;

    const newList = new ListLoader<Follows>({
      fetchData: async (params) => {
        const url = `users/${userId}/followers`;
        const response = await _API.get(url, { params });
        return response.data;
      },
      onLoad: (data) => {
        for (const user of data.items) {
          this.followers.set(user.id, user);
        }
      },
    });

    this.followersList.set(userId, newList);
    return newList;
  }

  getFollowingListLoader(userId: string) {
    const list = this.followingList.get(userId);
    if (list) return list;

    const newList = new ListLoader<Follows>({
      fetchData: async (params) => {
        const url = `users/${userId}/following`;
        const response = await _API.get(url, { params });
        return response.data;
      },
      onLoad: (data) => {
        for (const user of data.items) {
          this.following.set(user.id, user);
        }
      },
    });

    this.followingList.set(userId, newList);

    console.log(newList);
    return newList;
  }
}

const followsStore = new FollowsStore();

export default followsStore;

最佳答案

在 MobX 中,为了更改状态,您需要使用 action 。将您的 openActionMenu 设置/装饰为一个操作,或将状态更改代码提取到您装饰为操作以使其更清晰的另一个函数。

关于javascript - MobX 存储在 React Native 中未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111319/

相关文章:

react-native - 尝试从不同的线程同步调用函数 {w} - React Native Reanimated

javascript - 如何在 JavaScript 中获取 ISO 8601 周的开始和结束日期时间?

javascript - 我如何获得 Todo 的 Id

javascript - AppBar color secondary with Select material-ui-next

javascript - 自定义 Hook 内的 setState 调用不会更新状态

react-native - React Native : Can't use this. setState() 在 2D 数组内设置变量,但 this.state.x= 有效

javascript - 使用 jQuery 设置淡出 PreLoad 屏幕的时间

javascript (html5) - 我可以禁止两个键同时触发吗?

javascript - 按钮点击事件不起作用

javascript - react JSX "Parse Error: Unexpected identifier"