redux store state between page route

2019-04-16 16:42发布

setup:

  • @page1 loads list of items
  • @page1 i have a link to route to @page2
  • @page2 have dropdown list with items from @page1 via redux store/connect

works route> @page1 -> @page2

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

question how to be route -> @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?

2条回答
forever°为你锁心
2楼-- · 2019-04-16 17:08

How are the items from page 1 being populated?

If I'm understanding your question correctly you shouldn't need to worry about how to handle the items since they are stored in your redux store.

When you do a mapStateToProps you can define what data from the store you want available to the page 2 component.

查看更多
相关推荐>>
3楼-- · 2019-04-16 17:27

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

You can have your reducer setup like this

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 action can look like this

// 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>
        )
    }


}

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

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

查看更多
登录 后发表回答