我有一个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>
);
};
我想强制重新渲染的NavBar
与points
的值显示在按钮提交后的形式与价值给予输入没有重新加载页面。我尝试了useEffect
挂钩和useNavigate
从路由器,但不能解决这个问题。你们知道我怎么才能让它正常工作吗?
GitHub上的Repo如下:https://github.com/jerzy-jarczynski/react-rewards-app
我尝试了useEffect
来刷新NavBar
组件中的点,在currentPoints
从Redux useSelector
更改之后。我也试过在提交表单后将useNavigate
切换到'/'
。
我希望在按钮内的NavBar
组件中看到更新的points
值,而无需重新加载页面。
1条答案
按热度按时间gc0ot86w1#
您可以更改
pointsReducer
以仅更新状态中的points
字段,而不是用有效负载替换整个状态。