亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React-Redux UI 錯誤。圖像更新滯后

React-Redux UI 錯誤。圖像更新滯后

慕斯王 2023-05-11 14:23:13
我正在構建 MERN 電子商務應用程序,并且在從 Redux Store 中提取數據時遇到了一個奇怪的 UI 錯誤。從一個產品頁面切換到另一個頁面后,會顯示并更新舊產品圖像。如您所見:https://imgur.com/iU9TxJr在那里你可以看到減速器的代碼:export const productDetailsReducer = (  state = { product: { reviews: [] } },  action) => {  switch (action.type) {    case PRODUCT_DETAILS_REQUEST:      return { loading: true, ...state };    case PRODUCT_DETAILS_SUCCESS:      return { loading: false, product: action.payload };    case PRODUCT_DETAILS_FAIL:      return { loading: false, error: action.payload };    default:      return state;  }};還有行動代碼:export const listProductDetails = (id) => async (dispatch) => {  try {    dispatch({ type: PRODUCT_DETAILS_REQUEST });    const { data } = await axios.get(`/api/products/${id}`);    dispatch({      type: PRODUCT_DETAILS_SUCCESS,      payload: data,    });  } catch (error) {    dispatch({      type: PRODUCT_DETAILS_FAIL,      payload:        error.response && error.response.data.message          ? error.response.data.message          : error.message,    });  }};最后,有組件的代碼,我將 redux 存儲帶入頁面const ProductPage = ({ match }) => {  const dispatch = useDispatch();  const productDetails = useSelector((state) => state.productDetails);  const { loading, error, product } = productDetails;  useEffect(() => {    dispatch(listProductDetails(match.params.id));  }, [dispatch, match]);  console.log(product);  return (    <>      {loading ? (        <Loader />      ) : error ? (        <Message variant="danger">{error}</Message>      ) : (        <Row>          <Col md={8}>            <Image src={product.image} alt={product.name} fluid />          </Col>...rest of component's code....我知道甚至最好不要將 redux 用于單個產品,但我正在使用這個項目進行練習,而且我有點被困在這個項目上。
查看完整描述

1 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

您需要做的是在離開詳情頁面時清除所選商品。您可以使用 的返回函數來做到這一點useEffect。所以可能是這樣的:


useEffect(() => {

  dispatch(listProductDetails(match.params.id));

  

  return () => {

    dispatch(clearSelectedProduct());        

  }

}, [dispatch, match]);

并添加相應的 action 和 reducer 更改..


case CLEAR_SELECTED_PRODUCT:

  return { loading: false, product: { reviews: [] } }; 

這樣,當您到達產品詳情頁面時,之前的產品總是被清除。


查看完整回答
反對 回復 2023-05-11
  • 1 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號