2021年3月27日星期六

React UI doesn't update on reduc store change

I have a redux State HOC to manage the connection

I Have a problem when I add a new post to the store

import React, { useEffect } from "react";  import { connect } from "react-redux";    export default function withState(WrappedComponent) {    function mapStateToProps(reduxState) {      let state = {};      for(let t of Object.entries(reduxState)) {        state = {...state, ...t[1]}      }            return {        ...state,      };    }      return connect(      mapStateToProps,      null    )(function (props) {        useEffect(() => {}, [props.posts, props.comments]) /*tried this but didn't work*/      return (        <React.Fragment>          <WrappedComponent {...props} />        </React.Fragment>      );    });  }      

I am trying to make the program render the response from my back-end without me reloading the page manually

I tried using the useEffect

and I saw through the dev tools that the state change correctly

my reducer

import { GET_ALL_POSTS, CREATE_NEW_POST } from "../actions"    const initialState = {      posts: []  }    export default function postReducer(state = initialState, action) {              let newState = {...state}            switch(action.type){          case GET_ALL_POSTS:              return {                  ...newState,                  posts: [...action.posts],              }          case CREATE_NEW_POST:              const posts = [...newState.posts, action.post]              return {                  ...newState,                  posts              }          default:              return {                  ...newState,              }      }  }  

I also read that react changes doesn't respond to shallow copies so I changed the whole array in the post reduces when I add a new post

https://stackoverflow.com/questions/66838292/react-ui-doesnt-update-on-reduc-store-change March 28, 2021 at 12:03PM

没有评论:

发表评论