简体   繁体   中英

How to keep state when switch the component in Reactjs?

I have a component

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {stories: []};
    }

    componentDidMount() {
        $.get(Api.getList(), (result) => {
            const data = result;
            if (data) {
                this.setState((prevState) => ({
                    stories: data.stories
                }));
            }
        });
    }

    render() {
        if (this.state.stories.length == 0) {
            return (
                <Tpl>
                    <Loading/>
                </Tpl>
            );
        } else {
            return (
                <Tpl>
                    <Stories stories={this.state.stories}/>
                </Tpl>
            );
        }
    }
}

and everytime when I switch to this component, it will run constructor first. so the state will be empty.

what I want is if stories had items, it don't need to get data again.

is it any method to keep that state?

I think the best way to achieve this would be to use react-redux whereby you have a centralized store which maintains state to all the components and thus saving it from refreshing everytime the component loads

Here is a good article to help you get started with redux.

The other way to do what you want is to have you states saved in localStorage whereby on every component load you load data from localStorage and set to state initially and when updating a state also update the value there. Below is a sample method that you can follow for this approach.

constructor(props) {
    super(props);
    var stories = JSON.parse(localStorage.getItem( 'stories' )) || null
    this.state = {stories: stories};
}
componentDidMount() {

        $.get(Api.getList(), (result) => {
            const data = result;
            if (data) {
               JSON.stringify(localStorage.setItem( 'stories', data.stories));
               this.setState((prevState) => ({
                    stories: data.stories
                }));
            }
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM