Mobx在React中的实践-10086

本文展示了如何使用MobX库来管理React应用中的状态,创建了两个store(用户和帖子),并实现了从API获取数据的功能。当用户列表中的项被点击时,会更新当前用户ID并自动加载相应的帖子列表。所有这些交互都在组件中通过observer模式处理。
摘要由CSDN通过智能技术生成

创建Store

创建/store/usersStore/index.js

import { observable, action,runInAction } from "mobx";

const usersStore = observable(
  {
    users: [],
    setUsers(value) {
      this.users = value;
    },
    getUsers() {
      return this.users;
    },
    async fetchUsers() {
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/users`
      );
      const users = await response.json();
      runInAction(() => {
        this.setUsers(users);
      });
    },
  },
  {
    users: observable,
    setUsers: action,
    getUsers: action,
    fetchUsers: action,
  }
);

export default usersStore;

创建/store/postsStore/index.js

import { observable, action, autorun, runInAction, reaction } from "mobx";

const store = observable(
  {
    loading: false,
    currentUserId: "",
    posts: [],
    setLoading(loading) {
      this.loading = loading;
    },
    getLoading() {
      return this.loading;
    },
    setCurrentUserId(uid) {
      this.currentUserId = uid;
    },
    getCurrentUserId() {
      return this.currentUserId;
    },
    setPosts(value) {
      this.posts = value;
    },
    getPosts() {
      return this.posts;
    },
  },
  {
    loading: observable,
    currentUserId: observable,
    posts: observable,
    setLoading: action,
    getLoading: action,
    setPosts: action,
    getPosts: action,
    setCurrentUserId: action,
    getCurrentUserId: action,
  }
);

const getPostsById = async (uid) => {
  runInAction(() => {
    store.setLoading(true);
  })
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts?userId=${uid}`
  );
  const posts = await response.json();
  runInAction(() => {
    store.setPosts(posts);
    store.setLoading(false);
  });
};

// autorun(() => {
//     getPostsById(store.currentUserId);
// });

reaction(
  () => store.currentUserId,
  () => {
    getPostsById(store.currentUserId);
  }
);

export default store;

创建组件

/components/UsersList.jsx

import { List } from "antd";
import { useEffect } from "react";
import { observer } from "mobx-react-lite";
import usersStore from "../../store/usersStore";
import postsStore from "../../store/postsStore";

const UsersListUI = observer(function (props) {
  const handle = ({ id }) => {
    postsStore.setCurrentUserId(id);
  };
  return (
    <div style={{ width: 300 }}>
      <List>
        {usersStore.users.map((user) => (
          <List.Item key={user.id} onClick={() => handle(user)}>
            <span
              style={
                postsStore.currentUserId === user.id ? { color: "red" } : {}
              }
            >
              {user.name}
            </span>
          </List.Item>
        ))}
      </List>
    </div>
  );
});

export default function () {
  useEffect(() => {
    usersStore.fetchUsers();
  }, []);
  return <UsersListUI />;
}

创建组件:components/PostsList.jsx

import { List } from "antd";
import { observer } from "mobx-react-lite";
import postsStore from "../../store/postsStore";

const PostsList = observer(function (props) {
  if(postsStore.loading){
    return <span>loading</span>
  }
  return (
    <List>
      {postsStore.posts.map((post) => (
        <List.Item key={post.id}>
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              textAlign: "left"
            }}
          >
            <p>id: {post.id}</p>
            <p>title {post.title}</p>
            <p>body: {post.body}</p>
          </div>
        </List.Item>
      ))}
    </List>
  );
});

export default PostsList;

在App组件中引入

import "./App.css";
import PostList from "./components/PostList/index.jsx";
import UserList from "./components/UserList";

function App() {
  return (
    <div className="App" style={{
      display: "flex",
    }}>
      <UserList />
      <PostList />
    </div>
  );
}

export default App;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值