简体   繁体   中英

Using setState to set all state of react page

I have a page where I'm gonna take the whole state of the page and set it with some localstorage so I need to use SetState but not using some property like sane people do

Sane people

this.setState({ 
  stateProperty:someValue
})

Me (what I want to achieve)

this.setState({
  this.state: {someValues}
})

No, you don't. Sorry, you can't. You've accepted yourself that is sane people do like, but why are you trying to go insane code?

It's better to maintain for localStorage data with specified state:

state = {
  storeData: {} // or, [], or whatever your stored data type
}
componentDidMount() {
  const storeData = JSON.parse(localStorage.getItem('store-data'))
  this.setState({
     storeData
  })
}

Some people might suggest you to initialize localStorage data directly in the constructor. But I'm against it because I don't like to cause some side effect to the component.

PS: There' no side effect actually using localStorage data in the constructor. I have just suggested to use componentDidMount hook because you might need to call some api which will call to load the localStorage data and that time you might have some side effect. To ignore this, use componentDidMount hook because it's an asynchronous function which runs in background.

For set/get state from localStorage use this:

localStorage.setItem('store-state',JSON.stringify(this.state));
const storeState = JSON.parse(localStorage.getItem('store-state'));
this.setState(storeState);

With this code you able to store/reload your state from localStorage. notice, in setState no need to create any objects({}).

Maybe you could do something like this:

const updateState = window.localStorage.getItem('whatever');
let newState = Object.assign({}, this.state);
newState = updateState;
this.setState({newState});

Hope it works.

Looks like you can actually call a this.state={something} on constructor

This did the trick

constructor(props) {
        super(props);

          if ( typeof store.get([store.get("auth").ID]) === "undefined") {
              store.set([store.get("auth").ID], { localStorageData: {} });
          }

          this.state = {
              ...bla bla bla
          }

          this.state=Object.assign({}, this.state, this.state.localstore ) 
   }

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