问题:
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 )
}