React: Uncaught Typeerror: Cannot Read Property 'state' Of Undefined
Solution 1:
Application is stateless component. Not to say that arrow functions have lexical scoping of context.
Use props for stateless components.
constApplication = (props) => {
return (
<div> Hello world beginner: {props.comments}</div>
);
};
Or extend React.Component
classApplicationextendsReact.Component {
constructor() {
// init state
}
render() {
return<div> Hello world beginner: {this.state.comments}</div>
}
}
Solution 2:
Few Things:
*Stateless Functional Components
don't have state
, lifecycle
methods, and this
keyword.
*You need to connect General
and Application
component so that Application
component can you the state
value of General component
.
*Make Application
component as child of General component and pass the comments value in props
, and in Application
access the value by props.comments
.
Write it like this:
classGeneralextendsComponent {
constructor() {
super();
this.state = { comments: first_comment};
}
render(){
return (
<div><Applicationcomments={this.state.comments}/></div>
)
}
}
constApplication = (props) => {
return (
<div> Hello world beginner: {props.comments}</div>
);
};
render(<General/>, document.getElementById('container'));
Check the working example:
classGeneralextendsReact.Component {
constructor() {
super();
this.state = { comments: 'first_comment'};
}
render(){
return (
<div><Applicationcomments={this.state.comments}/></div>
)
}
}
constApplication = (props) => {
return (
<div> Hello world beginner: {props.comments}</div>
);
};
ReactDOM.render(<General/>, document.getElementById('container'));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid='container'/>
Solution 3:
In your class component you should be extending or subclassing React.Component
and when you do, that means you are going to be overriding the constructor()
functions of React.Component
classes with the one from General
class-component, but you don't want to do that, you still want to access React.Component
constructor()
so you need to pass in props
to the constructor and to super()
.
Next, when passing state as props to a functional component, you need to pass in props
as an argument to the functional component, otherwise when doing this for example:
importReactfrom'react';
constImageList = () => {
console.log(props.images);
return<div>ImageList</div>;
};
exportdefaultImageList;
you will get that same error you got. Imagine I am trying to access state from your General
class-based component into this ImageList
component above and I do have it imported to General
, it will give me the same error, because I have not passed props
as an argument to ImageList
functional component.
Post a Comment for "React: Uncaught Typeerror: Cannot Read Property 'state' Of Undefined"