页面路由之间的 redux 存储状态 [英] redux store state between page route

查看:48
本文介绍了页面路由之间的 redux 存储状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置:

  • @page1 加载项目列表
  • @page1 我有一个链接到@page2
  • @page2 通过 redux store/connect 有来自@page1 的项目的下拉列表

作品路线> @page1 -> @page2

如果流程转到@page1 -> @page2 就可以正常工作,因为它可以确保预加载项目.

it works ok if the flow goes @page1 -> @page2 since it ensures items to be preloaded.

问题如何成为路由 -> @page2

但是当它直接转到 @page2 时处理项目的最佳方法是什么,我应该以某种方式检测路由来源并再次加载项目 @page2 吗?

but what is the best way to handle items when it directly goes to @page2 , should i somehow detect the route origin and load items @page2 again?

推荐答案

有很多方法可以做到这一点,这个例子展示了如何使用 ComponentActions 来实现这一点

There are many ways to do this, This example showcases how to achieve this using Component and Actions

您可以像这样设置reducer

const app_default_data = {
    items: [],
    loaded: false,
}
function appReducer(app=app_default_data, action) {
    // your ap preducer code here.
    return app;
}
export default appReducer;

你的动作可能是这样的

// your loadAppData action will load data from server
const loadAppData = () => {
    // load the data from server
    // validate it
    // save data in your store.
    // change loaded to true in your store
    return { type: APP_DATA_LOADED, payload: data }
}

现在,在依赖数据存在的每个组件中,您可以执行类似的操作

Now, Inside every component that relies on the data to be present, you can do something like

const mapStateToProps = ( state, ownProps ) => {
    return {
        items: state.app.items,
        loaded: state.app.loaded,
    }
}

const mapDispatchToProps = ( dispatch, ownProps ) => {
    return {
        loadAppData: () => dispatch( loadAppData() ),
    }
}


let MyComponent = (props) => {

    if ( ! props.loaded ) {
        setTimeout( () => {
            props.loadAppData();
        }, 10);
    }


    if ( props.loaded ) {
        return (
            <h1>Data is loaded.</h1>
        )
    } else {
        return (
            <h1>Loading data, please wait...</h1>
        )
    }


}

注意:这里我以无状态组件为例,如果没有加载数据,我使用setTimeout调用Action.

Note: I have used stateless component as an example here, and am using setTimeout to call the Action if the data if not loaded.

如果您正在使用 React Class,您可以将 props.loadAppData(); 放在您的 componentDidMount 方法中,它就会起作用.

If you're using React Class you can place props.loadAppData(); within your componentDidMount method and it will work.

这篇关于页面路由之间的 redux 存储状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆