axios 提取数据前出错

ego6inou  于 2023-03-02  发布在  iOS
关注(0)|答案(1)|浏览(174)

我正在创建一个电子商务项目。
我想做的是从api中通过id获取单个产品数据,但在以下情况下会出现一些错误:

  • 刷新页面
  • 链接到页面非常快
  • 单击单个产品页面中的按钮,将更新redux中的状态

下面是错误和我的代码
我试图创建它的初始状态以避免错误,但它不工作。请帮助。

// singleListingSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { toast } from "react-toastify"
import customFetch from "../../utils/axios"

const initialState = {
  isLoading: false,
  isError: false,
  createSuccess: false,
  listing: {},
}

export const getSingleListing = createAsyncThunk(
  "singleListing/getSingleListing",
  async (id, thunkAPI) => {
    try {
      const { data } = await customFetch(`/listing/${id}`)
      return data.listing
    } catch (error) {
      return thunkAPI.rejectWithValue(error.response.data.msg)
    }
  }
)

const singleListingSlice = createSlice({
  name: "singleListing",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getSingleListing.pending, (state) => {
        state.isLoading = true
      })
      .addCase(getSingleListing.fulfilled, (state, { payload }) => {
        state.isLoading = false
        state.listing = payload
        toast.success(`done fetching`, {
          toastId: "success",
        })
      })
      .addCase(getSingleListing.rejected, (state) => {
        state.isLoading = false
        state.isError = true
        toast.error(`can't find listing, please try again`)
      })
  },
})

export default singleListingSlice.reducer
// singleListingPage.jsx
import { useState, useEffect } from "react"
import { useSelector, useDispatch } from "react-redux"
import { useParams } from "react-router-dom"

import {
  Searchbox,
  UserInfo,
  ReviewCard,
  OfferBox,
  Slider,
} from "../components"
import { getSingleProduct } from "../features/singleProduct/singleProductSlice"

const initialState = {
  condition: "",
  createdAt: "",
  createdBy: "",
  dealMethod: {
    meetUp: true,
    delivery: false,
  },
  description: "",
  meetUpLocation: "",
  name: "",
  photos: [],
  previousPrice: "",
  price: "",
  soldTo: "",
  status: "",
  updatedAt: "",
  _id: "",
}
const SingleListingPage = () => {
  const [listing, setListing] = useState(initialState)
  const { user } = useSelector((store) => store.user)
  const {
    listing: storeListing,
    isLoading,
    isError,
  } = useSelector((store) => store.singleListing)
  const { id: listingId } = useParams()
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(getSingleListing(listingId))
  }, [listingId])

  useEffect(() => {
    setListing(storeListing)
  }, [storeListing])

  if (isLoading) {
    return <h1>Loading...</h1>
  }

  if (isError) {
    return <h1>Error</h1>
  }

  const {
    condition,
    createdAt,
    createdBy,
    dealMethod,
    description,
    meetUpLocation,
    name,
    numOfFavorite,
    photos,
    previousPrice,
    price,
    soldTo,
    status,
    updatedAt,
    _id,
  } = listing


  let tradeMethod = []
  Object.entries(dealMethod).forEach((method) => {
    if (!method[1]) return
    tradeMethod = [...tradeMethod, method[0]]
  })

  return (
    <Wrapper>
      <div className="container">
        <Searchbox />
        <div className="bread-crumb">category / {name}</div>
        <SingleListingSlider photos={photos} />
        <section className="listing-information">
          <div className="details">
            <div className="row">
              <h3 className="name">{name}</h3>
              <div className="favorite">
                {numOfFavorite > 0 ? <FaRegHeart /> : <FaHeart />}
                <span>{numOfFavorite}</span>
              </div>
            </div>
            <h2 className="price">HK${price}</h2>
            <span>condition: {condition}</span>
            {/* <span>trade method: {tradeMethod}</span> */}
            <span>location: {meetUpLocation}</span>
          </div>
          <OfferBox />
        </section>
        <section className="section-description">
          <h2 className="title">Description</h2>
          <article>{description}</article>
        </section>
        <section className="section-review">
          <div className="col">
            <UserInfo {...user} />
          </div>
          <div className="col">
            <h2 className="title">reviews for @{name}</h2>
            <div className="reviews">
              <ReviewCard />
              <ReviewCard />
              <ReviewCard />
            </div>
          </div>
        </section>
      </div>
    </Wrapper>
  )
}

export default SingleListingPage

我尝试创建一个intialObject来阻止它,但没有效果

wmomyfyw

wmomyfyw1#

试着检查所有地方的NULL。创建对象,有setter和getter,并检查setter中的NULL。除此之外,我的猜测是API返回NULL。

相关问题