reactjs - 正确的代码流: dispatch actions and block, 还是 dispatch 他们提前验证?

标签 reactjs redux react-hooks redux-toolkit json-server

这是我自学前端开发一年后在Stackoverflow上的第一个问题。我已经找到了我的疑惑的答案,但由于这些问题是第三次返回,我认为是时候向 Web 提问了。

我正在尝试构建什么

我正在尝试构建一个图书馆服务, guest 用户可以在其中登录、预订书籍、添加到心愿单、还书等。对于前端,我使用的是 react , react-router , react-bootstrapredux-toolkit .由于我还不了解后端,所以我使用 json-server 获取数据, 它监视一个简单的数据库,其中有两个大对象:users和书 catalogue .

我认为的应用流程

代码中有一个<Catalogue />组件,它向 json-server' to get the data (with 发送请求使用效果 ), which is stored in the state. When data is fetched, it renders ` 组件,带有必要的信息和两个按钮。其中一个是为了预订一本书。保留按钮背后的逻辑是:

  • 验证IF当前用户不是管理员
  • 验证IF当前用户已经预订了这本书
  • 验证IF数据库中至少有一本书要预订

只有在一切正常的情况下,代码才会分派(dispatch)使用 createAsyncThunk 创建的操作在catalogueSlice .在这个 thunk 中,它从数据库中删除了这本书的副本并将结果传递给 extrareducers。更新状态。 handleClick 函数是 async并等待这个 Action 的结束。操作完成后,代码会分派(dispatch)另一个操作,即使用 createAsyncThunk 创建的操作在userSlice ,它更新数据库,将那本书添加到该用户的当前预订中,并像其他 thunk 一样,将结果传递给状态,并更新用户的状态。

我的疑惑和问题

我的主要问题

  1. 上述 IF 语句的正确位置在哪里?验证用户、当前预订和数据库中图书的存在性?在 React 组件中还是在 createAsyncThunk 中?我的意思是:验证是否必须分派(dispatch)一个 Action 更好,还是分派(dispatch)该 Action 并在之后阻止它更好?例如可以调用 dispatch 吗?在 thunk 内部使用 thunkAPI

我的其他疑问

  1. 使用 useAppSelector 检索状态通常更好吗?或者,在可能的情况下,将其传递给 child props

  2. 到现在为止,我已经reserve , addToWishlist , login , register , 这些都是用 createAsyncThunk 创建的,并在 extrareducers 中产生大量代码的切片。我打算添加更多,这将是向服务器发送请求的其他 thunk。这个工作流程好吗?我在后端做一些严重的逻辑错误?

  3. 没看懂,这是一个thunk的区别和一个 middleware .有什么有用的资源吗?

这是发送请求的两个主要thunk。抱歉,它们不是那么干净,但我认为这足以理解问题。

export const patchCatalogue = createAsyncThunk(
  'catalogue/patch',
  async ({book, userInfo}: {
    book: IBook;
    userInfo: IUserInfo;
  }, thunkAPI) => {
    const {
      id: bookId,
      book_status: {
        copies,
        history,
        current
      }
    } = book;
    const { 
      id: userId, 
      username 
    } = userInfo;
    try {
      const response = await axios.patch(
        `http://localhost:5000/catalogue/${bookId}`,
        {
          book_status: {
            copies: copies - 1,
            current: [...current, [userId, username]],
          }
        });
      if (response.status === 200) {
        const result = await thunkAPI.dispatch(reserve({ book, userInfo }))
        // console.log(result)
        return response.data;
      }
    }
    catch (error) {
      console.error(`PATCH failed - ${error}`)
    }
  },
);
export const reserve = createAsyncThunk(
  'user/reserve',
  async ({ book, userInfo }: {
    book: IBook;
    userInfo: IUserInfo;
  }, thunkAPI) => {
    const {
      id: userId,
      reservations: {
        current,
        history,
      }
    } = userInfo;

    try {
      const response = await axios.patch(`http://localhost:5000/users/${userId}`, 
      {
        reservations: {
          current: [...current, book],
          history: [...history],
        }
      });
      return response.data;
    }
    catch (error) {
      console.error(error)
    }
  }
);

这是 Button 组件,它分派(dispatch)这两个操作。

if (userInfo.role === 'user') {
        if (action === 'Book now!') {
          const alreadyBooked = userInfo.reservations.current.find(item => item.id === book.id)
          if (!alreadyBooked) {
            await dispatch(patchCatalogue({ book, userInfo }));
            dispatch(reserve({ book, userInfo }))
          }
          else {
            alert('The book is already reserved!')
          }
        }

最佳答案

主要问题的答案。

据我所知,上述 IF 语句的正确位置React 组件Dispatching an action 意味着在 App workflow 中涉及 Redux Store。所以涉及Store是没有用的,只是为了检查条件。它还有助于保持存储切片中的代码干净。

渴望知道您其他疑惑的答案。

关于reactjs - 正确的代码流: dispatch actions and block, 还是 dispatch 他们提前验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74392997/

相关文章:

javascript - 使用 redux-thunk 在去抖函数中分派(dispatch)操作

javascript - React Hooks,有条件地改变 onClick 函数内的状态,在下次点击时更新

reactjs - Context Api React 的问题

javascript - React hooks - setState 不更新状态属性

javascript - 不知道我做错了什么 - 获取不是函数错误

reactjs - 如何只发送图片消息? (也无需发送文本)

Angular ngrx 存储错误无法读取未定义的属性 'schedule'

javascript - Action 分派(dispatch)后渲染组件

css - React CSS Webpack Hashing & 使用 semantic-ui-sass, semantic-ui-react

javascript - 为什么突变会使 react 组件本身不可重用?