javascript - setState/use State in external function react -


considering pseudocode:

component.js

... import {somefunc} "./common_functions.js"  export default class mycomp extends component {     constructor(props) {         super(props);      this.somefunc = somefunc.bind(this);      this.state = {...};     }      _anotherfunc = () = > {         ....         this.somefunc();     }      render() {         ...     } } 

common_functions.js

export function somefunc() {     if(this.state.whatever) {...}     this.setstate{...} } 

how bind function somefunc() context of component? use in various components, makes sense collect them in 1 file. right now, error "cannot read whatever of undefined". context of this unknown...

you can't setstate outside of component because component's local state. if need update state shared, create store (redux store).

in case, can define somefunction @ 1 place , pass specific state variable(s) or entire state. after done in somefunction, return modified state , update in component using setstate.

export function somefunc(state) {     if(state.whatever) {...}     const newstate = { ...state, newvalue: whatevervalue }     return newstate }  _anotherfunc = () = > {         ....         const newstate = this.somefunc(this.state);        this.setstate({newvalue: newstate});     } 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -