React组件在Redux商店更新后无法重新呈现

vulvrdjw  于 2023-05-18  发布在  React
关注(0)|答案(1)|浏览(251)

我有一个React问题。我的组件NavBar在使用form更新存储区中的points值后,不会重新呈现points值。我想重新渲染组件,这样它就可以得到新的points值与useSelector挂钩,然后显示在按钮上的页面。
下面是我的Redux initialState代码:

const initialState = {
  points: '3100',
  rewards: [
    {...}              
  ],
};

我的pointsRedux文件:

// selectors
export const getAllPoints = state => state.points;

// actions
const createActionName = actionName => `app/points/${actionName}`;
const UPDATE_POINTS = createActionName('UPDATE_POINTS');

// action creators
export const updatePoints = payload => ({ type: UPDATE_POINTS, payload });

// subreducer
const pointsReducer = (statePart = [], action) => {
  switch (action.type) {
    case UPDATE_POINTS:
      console.log('redux', action.payload);
      return action.payload;

    default:
      return statePart;
  };
};

export default pointsReducer;

我的表单组件(没有导入):

// other imports
import { getAllPoints, updatePoints } from '../../../redux/pointsRedux';

const AddPointsWidget = () => {

  const currentPoints = useSelector(getAllPoints);
  const [newPoints, setNewPoints] = useState(currentPoints);
  const dispatch = useDispatch();

  const handleSubmit = e => {
    e.preventDefault();
    dispatch(updatePoints(newPoints));
  };

  return (
    <form className={styles.AddPointsWidget} onSubmit={handleSubmit}>
      <>...</>  
      <SubmitButton>
        {'Zmień punkty'}
      </SubmitButton>
    </form>
  );
};

和提交表单后不重新呈现的NavBar组件:

import { getAllPoints } from '../../../redux/pointsRedux';

const NavBar = () => {
  const points = useSelector(getAllPoints);

  return (
    <nav className={styles.NavBar}>
      <>...</>
      <PointsButton
        location={'NavBar'}
        amount={points}
        clickFunction={openPopUp}
      />
      <>...</>
    </nav>
  );
};

我想强制重新渲染的NavBarpoints的值显示在按钮提交后的形式与价值给予输入没有重新加载页面。我尝试了useEffect挂钩和useNavigate从路由器,但不能解决这个问题。你们知道我怎么才能让它正常工作吗?
GitHub上的Repo如下:https://github.com/jerzy-jarczynski/react-rewards-app
我尝试了useEffect来刷新NavBar组件中的点,在currentPoints从Redux useSelector更改之后。我也试过在提交表单后将useNavigate切换到'/'
我希望在按钮内的NavBar组件中看到更新的points值,而无需重新加载页面。

gc0ot86w

gc0ot86w1#

您可以更改pointsReducer以仅更新状态中的points字段,而不是用有效负载替换整个状态。

const pointsReducer = (statePart = initialState, action) => {
  switch (action.type) {
    case UPDATE_POINTS:
      console.log('redux', action.payload);
      return {
        ...statePart,
        points: action.payload
      };
    default:
      return statePart;
  };
};

相关问题