How To Avoid Using Setstate With Callback
I have the following react component (it works), but I am using a cb for setState. I would like to know how to refactory the code removing the cb from the code: this.setState({ vie
Solution 1:
I assume/ you assume you are using babel and ES7. If so, you can use async
instead.
using cb
openViewer(type, item) {
this.setState({ viewer: null, document: null }, () =>this.getViewer(type, item))
}
using async-await
asyncopenViewer(type, item) {
awaitthis.setState({ viewer: null, document: null });
this.getViewer(type, item)
}
We were tested this approach and it works fine in our environments.
using promises
Or if you are comfortable with promises .
exportclassDocumentComponentextendsReact.Component {
// override and extend setState setState(state) {
returnnewPromise((resolve) => {
super.setState(state, resolve);
});
}
//...//...openViewer(type, item) {
this.setState({ viewer: null, document: null })
.then(() =>this.getViewer(type, item))
}
}
Solution 2:
Why not this way?
Instead of storing UI elements in state, store the data that you want to use, like src and type in your case. Call getViewer
method from render it will return the proper ui items. By this way you don't need to worry about setState callback, whenever you update the value of type and src, react will update the ui automatically.
exportclassDocumentComponentextendsReact.Component {
constructor(props) {
super(props)
this.state = {
src: '',
type: '',
}
}
getViewer() {
switch (this.state.type) {
case'image': return<Imagerurl={this.state.src} />default: returnnull
}
}
handlerOnClick(item: Object) {
this.setState({
type: 'image',
src: item.src
})
}
render() {
const { tileData, classes } = this.propsreturn (
<divclassName={classes.root}><ThumbnailsstileData={tileData}handlerOnClick={item => this.handlerOnClick(item)} />
{this.getViewer()}
</div>
)
}
}
exportdefaultDocumentComponent
Solution 3:
Try this:
setViewer(type, item) {
switch (type) {
case'image':
const node = (
<Imagerurl={item.src} />
);
this.setState({ viewer: node, document: item });
break;
default:
this.setState({ viewer: null, document: null });
}
}
openViewer(type, item) {
this.setViewer(type, item);
}
Post a Comment for "How To Avoid Using Setstate With Callback"