简体   繁体   English

我应该使用什么来代替 useSelector 或 mapStateToProps?

[英]What should I use instead of useSelector or mapStateToProps?

What should I use instead of useSelector or mapStateToProps ?我应该使用什么来代替useSelectormapStateToProps Those run multiple times and change all values to the last one.那些运行多次并将所有值更改为最后一个。

I have an e-commerce app, ProductDetails component contains product reviews and I map those to the ProductReview component to get user info that gets from user Id.我有一个电子商务应用程序, ProductDetails组件包含产品评论,我将这些评论映射到ProductReview组件以获取从用户 ID 获取的用户信息。

ProductDetails.js产品详情.js

import React, { useEffect } from "react";
import ProductReview from "../components/ProductReview";
import { useSelector, useDispatch } from 'react-redux';
import { getProductDetailsById } from "../Store/actions/productActions";

export default function ProductDetails(props) {
    const dispatch = useDispatch()
    const product = useSelector((state) => state.product)

  useEffect(() => {
    const { id } = props.match.params;
    const payload = {
      params: {
        id,
      },
    };
    dispatch(getProductDetailsById(payload));
    
  },[dispatch, props.match.params]);

  return (
    <div>
      {product.productDetails.reviews && 
        product.productDetails.reviews.map((item , index) =>    
        (
           <li key={item.userId}>
              <ProductReview key={item.userId} userId={item.userId} 
                             review={item.review}/>
           </li> )
               )}
        )}
</div>
  );
}

ProductReview.js ProductReview.js


import React,{ useState, useEffect } from 'react';
import { getUSerById } from '../Store/actions/userAction';
import {useDispatch , useSelector} from 'react-redux';

export default function ProductReview(props) {
  const dispatch = useDispatch()
  const user = useSelector(state => state.user)
  
const {userId} = props;
  
  useEffect(() => {
    const payload = {
      params : {
        userId
      }
    }
    dispatch(getUSerById(payload))  
  },[userId]);

    
 return (
    <div>
        {user && user.user.firstName} : {props.review}
    </div>
  )
}

this part of the code runs multiple times and changes all user info values (user first name) to the last one.这部分代码运行多次并将所有用户信息值(用户名)更改为最后一个。 **All product reviews firstName s change to the last one ** all same name **所有产品评论firstName s 更改为最后一个 ** 所有相同的名称

  const user = useSelector(state => state.user)

Is there any way to get rid of this??有没有办法摆脱这个?? It runs currently when using Axios in the ProductReview component with useState() , but I want to use redux.它当前在ProductReview组件中使用 Axios 和useState() ,但我想使用 redux。

userReducer.js userReducer.js

import { userConstants } from "../actions/Types";

const initState = {
  user: {},
  loading: false,
  error: null
};

export default (state = initState, action) => {
  console.log(action.payload)
  switch(action.type){
    case userConstants.GET_USER_BY_ID_SUCCESS:
      return state = {
        ...state,
        user : action.payload.user,
        loading: false,
        error: null
      }
    case userConstants.GET_USER_BY_ID_FAILURE:
      return state = {
        state,
        error: action.payload.error
      }  
    default:
      return state
  }
}

From what I understand in the comments you need to store all users in your redux store in some way.根据我在评论中的理解,您需要以某种方式将所有用户存储在您的 redux 存储中。 For example you could do something like the following:例如,您可以执行以下操作:

  1. Change initState with:使用以下命令更改initState

     const initState = { users: {}, loading: false, error: null };
  2. Change GET_USER_BY_ID_SUCCESS reducer with (please pay attention that I'm using user.id , but maybe your id is stored in some other property):更改GET_USER_BY_ID_SUCCESS减速器(请注意我使用的是user.id ,但也许您的 id 存储在其他一些属性中):

     case userConstants.GET_USER_BY_ID_SUCCESS: return state = { ...state, users: { ...state.users, [action.payload.user.id]: action.payload.user }, loading: false, error: null }
  3. Change useSelector with:将 useSelector 更改为:

     const users = useSelector(state => state.users)
  4. Add:添加:

     const user = users[props.userId]

In this way you should have the correct user.通过这种方式,您应该拥有正确的用户。 If I miss something please tell me.如果我错过了什么,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我应该使用 useselector/useDispatch 而不是 mapStateToProps - Should I use useselector/useDispatch instead of mapStateToProps 如何像 mapStateToProps 这样的类组件中的 useSelector 一样使用 - How to use like the useSelector in Class Component like mapStateToProps 我什么时候应该在 useSelector() 中使用自定义相等 function? - When should I use a custom equality function in useSelector()? 我应该使用全局变量吗?如果不是,那又是什么? (JavaScript)的 - Should I use a global variable and if not, what instead? (Javascript) 我应该使用什么而不是document.write作为弹出窗口 - what should I use instead of document.write for a popup 我应该用什么来代替 ng-repeater - what should i use instead of ng-repeater 我应该使用什么而不是 document.domain 来获取域? - What should I use instead of document.domain to get the domain? 不推荐使用 jQuery 切换功能。 我应该用什么代替? - jQuery toggle function is deprecated. What should I use instead? Eval是邪恶的...那么我应该使用什么呢? - Eval is evil… So what should I use instead? 在 Observable 上使用 await 时,我应该使用什么来代替 toPromise()? - What should I use instead of toPromise() when using await on an Observable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM