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,
value={{data:this.state.data}}
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.