在Redux React JS中重定向后,无法从存储中检索状态

问题描述 投票:0回答:1

我正在使用React JS + Redux开发Web应用程序。我是React的新手。我现在正在做的是尝试在一个页面上设置状态,然后在重定向后检索另一个页面中的状态。

我有一个名为EventListComponent的Component,它显示了事件列表。在该组件内部,我更改了调用事件的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内部,我试图检索在上一页中设置的状态的事件字段。但我无法找回它。我的问题是

  1. 重定向到新页面后,(还原商店的)状态是否重置?
  2. 我的代码出了什么问题?
  3. 如果我正在做的不是正确的方法,那么在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);
javascript reactjs redirect redux redux-store
1个回答
0
投票

您可能没有在setEditingEvent操作中正确设置类型,并且reducer返回初始状态,因为它没有达到EVENT_SET_EDITING_EVENT

© www.soinside.com 2019 - 2024. All rights reserved.