每条路线更改后都有组件状态相乘的副作用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每条路线更改后都有组件状态相乘的副作用相关的知识,希望对你有一定的参考价值。

我出于练习目的制作SPA Web应用程序,但是在React Rendering中遇到问题。我的App通常只有两条工作路径HomeUploadHome Route从API获取数据并将其显示在主体组件中。使用Upload,我可以将产品上载到数据库...除“ Home Page ...”之外,其他一切工作正常

当我从另一条路线回到Home时,先前的状态保持不变,但由于某种原因,该状态会成倍增加,而evrything却会变倍,这意味着获取的数据会变倍。.请帮助我... 。显示获取数据的我的应用的主体组件

//Importing Redux Action Creators
import getProducts, deleteProduct from "../Features/actions/productActions"
const Body = (getProducts, deleteProduct, productState)=>
    const products, loading, error = productState; //Destructuring redux State

     //Fetching data using redux actions inside useEffect hook
    useEffect(()=>
    getProducts()
    ,[getProducts])

    //Providing the payload as id for Redux Actions
    const deleteProducts = (id)=>
        deleteProduct(id)
    

    return (
        <div className="display-flex width-full flex-wrap justify-content-center">
            //Some Loading Logic for displaying data
            !loading && !error && products?products.map(product=>(
                product.data?product.data.map(d=>(
                  //This is the component which displays the fetched data as bootstarp card
                    <BodyDiv
                        key=uuid.v4()
                        imgSrc=d.imgSrc
                        title=d.title
                        details=d.details
                        description=d.description
                        onClick=()=>deleteProducts(d._id)
                    />    
                )):product.map(d=>(
                    <BodyDiv
                    key=uuid.v4()
                    imgSrc=d.imgSrc
                    title=d.title
                    details=d.details
                    description=d.description
                    onClick=()=>deleteProducts(d._id)
                /> 
                ))
            ))
            : loading&&!error
            ? <div className="vertical-center-strict horizontal-center-strict">Loading.......</div>
            : <div className="vertical-center-strict horizontal-center-strict">No Internet!</div>
        
        </div>
    )

//The layout for displaying fetched data
const BodyDiv = (props)=>
    return(
        <div className="container-div width-full card tiny-padding align-self-start">
        <img title=props.title className="img-responsive hover-filter" src=props.imgSrc/>
        <h2 className="text-align-center">props.title</h2>
        <h5>props.details</h5>
        <p className="text-align-justify">props.description</p>
        <button 
        className="btn btn-danger"
        onClick=props.onClick
        >Delete</button>
        </div>
    )   
 
//mapping & dispatching state to props from redux
const mapStateToProps = (state)=>(
    productState: state.productState
)
//React-Redux Connect to connect the component with Store
const conn = connect(mapStateToProps, getProducts, deleteProduct)(Body)

export default conn;
我的Redux状态的动作创建者和减速器
//Using redux-thunk for asynchronus middleware
export const getProducts = (payload)=>(dispatch)=>
   return fetch("/api/products") //URL
    .then(res=>
        dispatch(
            type:FETCHING_PRODUCTS //While fetching data
        )
        if(!res.ok)
            dispatch(
                type: ERROR_GET_PRODUCTS //If fetch fails then executes
            )
        
    return res.json();
    )
    .then(json=>
        if(json)dispatch(
        type: FETCHED_PRODUCTS,
        payload: json //Fetched json data as payload
    )
)
    .catch(err=>
        console.log("Error!! failed to fetch data: "+ err)
    )
 

//Reducer Function

//initial state
const initialState = 
  products: [], //this the state where Fetched data gets injected...
  loading: true,
  error: false,
;

const productReducer = (state = initialState, action) => 
  switch (action.type) 
    case FETCHING_PRODUCTS:
      return 
        ...state,
        loading: true,
      ;
    case FETCHED_PRODUCTS:
      return 
        ...state,
        products: state.products.concat(action.payload), //I don't know but I doubt here is the problem
        loading: false,
        error: false,
      ;
    case ERROR_GET_PRODUCTS:
      return 
        ...state,
        loading: false,
      ;
    default:
      return state;
  
;

export default productReducer;

我相信useEffect()挂钩或Reducer Function出了点问题。.有些人会说我应该尝试将products

state用作useEffect依赖项,但这导致了这种情况更糟糕的是……请大家帮我!!!自1天以来,我一直在尝试解决此问题...谢谢!

我出于练习目的制作SPA Web应用程序,但在使用React Rendering时遇到了麻烦。我的App通常只有两个工作路线,即Home&Upload。本地路由从API提取数据&...

答案

是的,问题似乎就在您认为的位置

 return 
        ...state,
         // the problem is here, you are adding products when in reality you just be just replacing them
        products: state.products.concat(action.payload), //I don't know but I doubt here is the problem
        loading: false,
        error: false,
      ;

以上是关于每条路线更改后都有组件状态相乘的副作用的主要内容,如果未能解决你的问题,请参考以下文章

如何使用自定义历史记录对象在我的主要App组件中侦听路线更改?

Sails.js 全局 CORS 配置不起作用,每条路线是

useState 函数在功能组件中不起作用

UI Router 1.0 状态更改事件不起作用

当我更改路线时,Laravel ajax 搜索不起作用

自动完成 Mui 测试,模拟更改不起作用