简体   繁体   English

具有组件 State 的副作用在每次路由更改后乘以

[英]Having Side Effect of Component State Multiplying after each Route Change

I'm making a SPA Web Application for practice purpose but having trouble with React Rendering..My App usually has only two working routes Home & Upload .我正在制作一个用于练习目的的 SPA Web 应用程序,但在 React Rendering 时遇到问题。我的应用程序通常只有两条工作路线HomeUpload Home Route Fetches data from an API & displays it in the Body Component..With Upload I can upload products to the Database...Everything works fine except the Home Page...主页路线从 API 获取数据并将其显示在正文组件中。通过上传我可以将产品上传到数据库...除了主页之外一切正常...

When I come back to Home from another route the previous state remains same but for some reason the state gets multiplied & evrything just gets doubled I mean the fetched data gets doubled..Please help me....当我从另一条路线回到家时,以前的 state 保持不变,但由于某种原因,state 成倍增加,而 evrything 只是加倍,我的意思是获取的数据加倍..请帮帮我....

My App's Body Component where Fetched data is displayed 我的应用程序的正文组件,其中显示了获取的数据
//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;
My Redux State's Action Creators & Reducer 我的 Redux State's Action Creators & Reducer
 //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;

I believe that something is wrong with the useEffect() hook or Reducer Function ..Some people would say that I should try using products state as useEffect dependencie but that makes the situation worse...Please guys help me... I have been trying to fix this since 1 day...Thanks!!我认为 useEffect() 钩子或 Reducer Function 有问题。有些人会说我应该尝试使用产品state作为 useEffect 依赖项,但这会使情况变得更糟...请大家帮助我...我一直从 1 天开始就试图解决这个问题......谢谢!

Yes problems seems to be where you think it is是的,问题似乎在你认为的地方

 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,
      };

replace this to将其替换为

return {
        ...state,
        products: action.payload
        loading: false,
        error: false,
      };

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM