简体   繁体   English

当 redux state 更改时,React 组件不会更新

[英]React component not updating when redux state changes

I have a React component that maps state to props to get data via redux. Everything works fine with the action and the value being updated properly in the reducer.我有一个 React 组件,它将 state 映射到道具以通过 redux 获取数据。一切正常,动作和值在 reducer 中正确更新。 My only problem is that when the state value changes, I want my component to re render so that it is always displaying the most up to date value in the reducer.我唯一的问题是,当 state 值发生变化时,我希望我的组件重新呈现,以便它始终显示 reducer 中的最新值。 As of right now I have to call a separate function that refreshes the component, but I'd rather have it automatically re render every time that value changes in the reducer.截至目前,我必须调用一个单独的 function 来刷新组件,但我宁愿让它在每次 reducer 中的值发生变化时自动重新渲染。

Action:行动:

export const createPickup = (selected, pickups) => dispatch => {
  let icon;
  icon = check(selected);
  pickups.icon = icon;
  return API('/createPickUp/', {
    ...pickups,
  })
    .then(res => {
      dispatch({type: types.CREATE_PICKUP, res});
    })
    .catch(err => console.log(err));
};

Reducer:减速器:

const initialState = {
  pick: [],
};
export default function pickup(state = initialState, action) {
  switch (action.type) {
    case types.GET_PICK:
      return {
        pick: action.pickup,
      };
    case types.CREATE_PICKUP:
      return {
        pick: [action.res, ...state.pick],
      };
    case types.DEL_GAME:
      return {
        pick: state.pick.filter(p => p._id !== action.id),
      };
    case types.START_GAME:
      return {
        pick: state.pick.map(p =>
          p._id === action.id ? {...p, start: true} : p,
        ),
      };
    case types.STOP_GAME:
      return {
        pick: state.pick.map(p =>
          p._id === action.id ? {...p, stop: true} : p,
        ),
      };
    default:
      return state;
  }
}

Use useSelector hook in Functional Component as it automatically subscribes to the state and your component will re-render.在功能组件中使用 useSelector 挂钩,因为它会自动订阅 state,您的组件将重新呈现。 If you are using Class Component then use connect() from redux and mapStateinProps.如果您使用的是 Class 组件,则使用 redux 中的 connect() 和 mapStateinProps。

I am assuming you have passed the reducer to the global Store.我假设您已将 reducer 传递给全局商店。 Now... make sure you have the up to date value in your component.. try consoling it like this...现在......确保你的组件中有最新的值......尝试像这样安慰它......

import {useSelector} from 'react-redux';
const YourCmponent = () => {
 
 const reduxState = useSelector(state => state);
 console.log(reduxState); 

 return <div>Your Content</div>

}

That way you can get access to the redux store.这样您就可以访问 redux 商店。 And you don't need to make any other function for updating component You will always get updated value here.而且您不需要为更新组件制作任何其他 function您将始终在此处获得更新的值。

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

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