简体   繁体   中英

Pass this.state variable through App Context

When I set the array data using the function getData() then try to call it in the function updateData() I get an error saying the this.state.data is undefined. Any thoughts on how I can pass a this.state variable from one function to another function in the app context provider?

Example code is below:

Any thoughts? Thank you!

export class AppProvider extends React.Component {
         constructor(props) {
           super(props);
           (this.state = {
             data: [],
           });
         }

         getData = async () => {
            const data = "abc"
            this.setState({ 
                data,
            });
        }

        updateData = async () => {
          console.log(this.state.data)
}

         render() {
           return (
             <AppContext.Provider value={this.state}>
               {this.props.children}
             </AppContext.Provider>
           );
         }
       }

Three Things i would like to say,

  1. you want to add the state variables separately so you want to do value={{data:this.state.data}}
  2. if you plan on using these functions in another component you want to add these functions to the value prop as well
  3. remove the async from the functions since there is no Promise to be resolved

     export class AppProvider extends React.Component { constructor(props) { super(props); this.state = { data: [] }; } getData = () => { const data = "abc"; this.setState({ data }); }; updateData = () => { console.log(this.state.data); }; render() { return ( <AppContext.Provider value={{ data: this.state.data, getData: this.getData, updateData: this.updateData }} > {this.props.children} </AppContext.Provider> ); } }

checked this in a small example, CodeSandbox here

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