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...

问题:

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

回答1:

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.


回答2:

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.


回答3:

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 ) 
   }
  • 发表于 2018-09-02 08:59
  • 阅读 ( 258 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除