What I'm trying to achieve here is, I want the value to be updated in the imported class B's state by calling the B's function init() from the class A. I'm initializing a new Object of B class and calling the init function through the object.
Class A
import B from 'b.js'
class A extends Component{
componentDidMount(){
const b=new B();
b.init("hey");
}
}
In Class B: I'm updating the state using the init function, but it appears that I'm getting setState is not a function error. I have also tried binding init function in the constructor, but the error stays the same.
class B extends Component{
constructor(props){
super(props);
state = {
text:""
}
}
init=(text)=>{
this.setState({text})
}
}
B
and a prop for the text.) Please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the[<>]
toolbar button). Stack Snippets support React, including JSX; here's how to do one.setState
on a unmounted component, that doesn't make any sense. If you want to set the initial state, just do ->Object.assign(this.state, {text})