javascript - 在 Redux React JS 中重定向后无法从存储中检索状态
问题描述
我正在使用 React JS + Redux 开发一个 Web 应用程序。我是 React 的新手。我现在正在做的是尝试在一个页面上设置状态,然后在重定向后在另一个页面中检索状态。
我有一个名为 EventListComponent 的组件,它显示事件列表。在该组件内部,我更改了调用事件的 reducer 的状态。
这是我调用的 reducer 函数。
import * as EditEventActions from '../actions/edit.event.actions';
export default function (state = { }, action){
switch (action.type)
{
case EditEventActions.EVENT_SET_EDITING_EVENT:
return { ...state, event: action.payload }
default:
return state;
}
}
我在重定向到这样的另一个页面之前触发了这些操作。
this.props.setEditingEvent(event);
this.props.history.push({
pathname : '/event/'+ event.id +'/edit'
});
在新页面中,我呈现名为 EditEventComponent 的组件。
这是 EditEventComponent 的定义
export class EditEventComponent extends React.Component{
constructor(props)
{
super(props);
alert(this.props.event.id)//cannot retrieve event here
}
render(){
return (
<h4>This is the Edit Event component</h4>
);
}
}
function mapStateToProps(state)
{
return {
event: state.editEvent.event
};
}
function matchDispatchToProps(dispatch)
{
return bindActionCreators({
}, dispatch);
}
const enhance = compose(withWidth(), withStyles(themeStyles, { withTheme: true }), connect(mapStateToProps, matchDispatchToProps))
export default enhance(EditEventComponent);
如您所见,在 EditEventComponent 内部,我试图检索在上一页中设置的状态的事件字段。但我无法找回它。我的问题是
重定向到新页面后(redux 商店的)状态是否重置?
我的代码有什么问题?
如果我所做的不是正确的方法,那么在 React Redux 中将对象从一个页面传递到另一个页面的最佳方法是什么?
这是我的行动
export const EVENT_SET_EDITING_EVENT = "(EVENT) SET EDITING EVENT";
export const setEditingEvent = (data) => ({
type: EVENT_SET_EDITING_EVENT,
payload: data
});
这是减速机
import * as EditEventActions from '../actions/edit.event.actions';
export default function (state = { }, action){
switch (action.type)
{
case EditEventActions.EVENT_SET_EDITING_EVENT:
return { ...state, event: action.payload }
default:
return state;
}
}
我也以这种方式公开 EventListComponent。
const enhance = compose(withWidth(), withStyles(themeStyles, { withTheme: true }), connect(mapStateToProps, matchDispatchToProps))
export default enhance(EventListComponent);
解决方案
您可能没有正确设置类型,setEditingEvent
并且减速器返回初始状态,因为它没有命中EVENT_SET_EDITING_EVENT
推荐阅读
- c# - 在具有多个连接 EF 的 Linq 查询中计数
- javascript - 如何在 HTML 中获取网络请求 URL 列表(浏览器背景)
- mysql - 需要帮助 MySQL 查询
- trace - 带有 Microprofile OpenTracing 分布式跟踪的 Quarkus 不起作用
- batch-file - 如果子文件夹中的文件被修改,则将文件从一个文件夹复制到另一个文件夹
- windows - Edge-Chromium - 代理服务器的注册表设置无法立即工作
- javascript - 在引导程序中切换时如何获取导航栏的高度?
- maven - 如何在 IntelliJ 中更新环境变量
- sql - 如何在选择查询中获取组的先前记录日期
- javascript - 我追加输入字段,然后我试图在同一个输入上执行触发事件但不工作