I have to call function inside constructor as working from call backs which i have to include in constructor but this is "undefined" in constructor.
class XXXXX extends React.Component {
constructor(props) {
super(props);
this.state =
{
chargebeeInstance : windowChargebeeinit({
site: "xxxxxxxxxxxxx-test"})
}
this.statechargebeeInstancesetCheckoutCallbacks(function(){
return{
close:function(){
this.moveToNextStep();
}
}
})
}
moveToNextStep(){
this.props.jumpToNextStep(3);
}
I am not able to call moveToNextStep as this is undefined
this is scope issue, you have to preserve scope before this.statechargebeeInstancesetCheckoutCallbacks function mentioned below
class XXXXX extends React.Component {
constructor(props) {
super(props);
const me = this
this.state =
{
chargebeeInstance : windowChargebeeinit({
site: "xxxxxxxxxxxxx-test"})
}
this.statechargebeeInstancesetCheckoutCallbacks(function(){
return{
close:function(){
me.moveToNextStep();//scope issue, this will not be available here
}
}
})
}
moveToNextStep(){
this.props.jumpToNextStep(3);
}
Hope this will help
You need to bind the function up to the current closure. Try this:
class XXXXX extends React.Component {
constructor(props) {
super(props);
// I believe this is what you are missing.
this.moveToNextStep = this.moveToNextStep.bind(this)
this.state = {
chargebeeInstance : windowChargebeeinit({
site: "xxxxxxxxxxxxx-test"
})
}
this.statechargebeeInstancesetCheckoutCallbacks(function(){
return{
close:function(){
this.moveToNextStep();
}
}
})
}
moveToNextStep(){
this.props.jumpToNextStep(3);
}
}
Related
I am unable to access class variable inside a function, following is my code:
export class MyClass extends React.Component<{}, {}>{
public myArray: string[]; //I want to access this variable
constructor() {
this.state = { name: "" }
}
private _hello = () => {
console.log(this.state.name);
console.log(this.myArray) //this lines throws undefined
}
render(){
<button onClick={this._hello}>Click</button>
}
}
Bring the function variable outside constructor. Btw render method should be outside constructor.
Try not to use private and public on react, here is some explanation, you could use:
const myArray: string[]; //I want to access this variable
export class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
}
}
hello = () => {
console.log(this.state.name);
console.log(myArray) //this lines throws undefined
}
render(){
return (
<button onClick={this.hello}>Click</button>
)
}
}
Am new to reactjs and am implementing a to do app using controlled component but am getting an error. Type Error: this.state is null!
Have you initialized your state in a constructor? You can do this by creating a constructor function in your class, e.g.
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {todoList: []};
}
Then you can add your todo's by doing this:
let todoListChange = this.state.todoList;
todoListChange.push("Clean my toilet");
this.setState({todoList: todoListChange});
You have not initialized your state. Default state is null.
class App from React.Component {
constructor (props) {
super(props);
this.state = { todos: [] }
}
render () {
// your implementation
}
}
So I am building my first react project and stumbled upon following problem:
In my App.js (main application) I got a function and render my components:
class App extends Component {
constructor(props) {
super(props);
this.candidateCounter = 0;
this.setCandidateVote = this.setCandidateVote.bind(this);
}
...
setCounter (name) {
this.candidateCounter++;
console.log(this.candidateCounter);
}
render() {
...
<Candidates setCounter={this.setCounter} />
}
}
The child component Candidates.jsx has another function and thus calls another component:
export class Candidates extends React.Component {
constructor(props) {
super(props);
this.AppProps = props;
}
...
registerVote(name) {
...
this.AppProps.setCounter(name);
}
render() {
...
<MyButton id={this.state.candidates[i].name} register={this.registerVote} />
}
And the last component MyButton.jsx looks like this:
export class MyButton extends React.Component {
constructor(props) {
super();
this.ParentProps = props;
this.state = { active: false }
}
buttonActiveHandler = () => {
this.setState({
active: !this.state.active
});
if (this.state.active === false) {
this.ParentProps.register(this.ParentProps.id);
}
else {
...
}
}
render() {
return (
<Button content='Click here' toggle active={this.state.active} onClick={this.buttonActiveHandler} />
);
}
}
I have successfully debugged that all functions calls are working except when the grandchild MyButton has triggered the registerVote() function in my Candidates module. Logging in this method gets printed but it cannot call this.AppProps.setCounter() from the parent App. I receive the following error:
TypeError: Cannot read property 'setCounter' of undefined
I hope this wasn't too complicated explained, any help is appreciated :)
Simply bind the function in the constructor of the class as #qasimalbaqali stated in his comment.
constructor(props) {
super();
this.registerVote = this.registerVote.bind(this);
}
// parent class
export default class HomeScreen extends React.Component {
constructor(props){
super(props);
this.state = {
password: '',
username:'',
session: 'mani',
};
}
authentication(){
const self = this;
axios.post('/api/users/login/', {
password: this.state.password,
username: this.state.username
})
.then(function (response) {
console.log(response);
var sessionid=response.headers["set-cookie"][0].split('Secure,').pop().split(';').shift();
self.setState({session: sessionid });
})
.catch(function (error) {
console.log("Invalid username/password");
});
}
render(){
return(<Session sessid={this.state.session}/>);
}
}
export default class Session extends Component {
constructor(props){
super(props);
this.sessionVariable = this.props.sessid;
}
render(){
console.log(this.props.sessid); // here i am getting updated value
console.log("constructor "+this.sessionVariable); // here i can't able to get updated value
return (<View></View>);
}
}
//child class
import React, { Component } from 'react'
import { View, Text } from 'react-native'
export default class Session extends Component {
constructor(props){
super(props);
this.state = {
sessid: this.props.sessid
}
}
componentWillReceiveProps(nextProps){
const { sessid } = nextProps;
if (sessid !== this.state.sessid) {
this.setState({sessid});
}
}
render(){
console.log(this.props.sessid);
console.log("dummy"+this.state.sessid);
return (<View></View>);
}
}
How to get updated data into constructor in React
Can you please give me the quick solution
I need to update the data in constructor . Then only I am able to call the global variable throughout the all components
How to get updated data into constructor in React
Can you please give me the quick solution
I need to update the data in constructor . Then only I am able to call the global variable throughout the all components
Add your props value inside the state and update it using componentWillReceiveProps ' lifecycle.
constructor(props) {
super(props);
this.state = {
sessid: this.props.sessid;
};
}
componentWillReceiveProps(nextProps){
const { sessid } = nextProps;
if(sessid !== this.state.sessid) {
this.setState({sessid});
}
}
You can use states to check that current condition, let me explain it with an example,
This is the constructor with initial state for the data toggle
constructor(props){
super(props);
this.state = {
toggle: true;
}
}
Update the existing state, do this
this.setState({ toggle: false });
Make sure you are using the above code inside an arrow function or else bind the .this
If you want more info comment that below...
The only reason that it doesn't show the updated value is because constructor is called only on the initial mount of the component and hence whatever class variable is set in constructor based on props, it won't be updated if the props change.
Second: setting a state or a class variable which is directly derivable from props is an anti pattern and you should just use props directly in render
export default class Session extends Component {
render(){
console.log(this.props.sessid);
return (
<View>
</View>
)
}
}
Still if you want to update the class variable based on, you can make use of componentWillReceiveProps function like
componentWillReceiveProps(nextProps) {
if(nextProps.sessid !== this.props.sessid) {
this.sessionVariable = nextProps.sessid;
this.forceUpdate(); // called to cause a re-render
}
}
or
export default class Session extends Component {
constructor(props) {
super(props);
this.state = {
sessionVariable: props.sessid
}
}
componentWillReceiveProps(nextProps) {
if(nextProps.sessid !== this.props.sessid) {
this.setState({ sessionVariable: nextProps.sessid});
}
}
render(){
console.log(this.state.sessionVariable);
return (
<View>
</View>
)
}
}
In your constructor define a state:
constructor(props) {
super(props);
this.state = {
sessionVariable: props.sessid;
};
}
Now, in your render():
console.log(props.sessid);
console.log("constructor "+ this.state.sessionVariable);
The constructor for a React component is called only before it is mounted. If you define some variable in constructor, it will store its value not reference and will not be re render again.
To change any value defined in constructor, you need to change it in updating phase of react (ComponentWillReceiveProps) and then call the
this.forceUpdate(); // to render the component
eg.
componentWillReceiveProps(nextProps) {
if(this.props.sessid !== nextProps.sessid) {
this.sessionVariable= nextProps.sessid;
this.forceUpdate();
}
}
Or you can directly use props in render function.
I am trying to write my first react control. Here is what I have written
import React from 'react';
import DimensionPickerAction from '../actions/DimensionPickerActions.js';
import MovieLensAppStore from '../stores/MovieLensAppStore.js';
class DimensionPicker extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], currentItem: '' };
}
getInitialState() {
this.state = {
items: MovieLensAppStore.getAttributes(this.props.dimension),
currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
};
}
onSelectionChange(newValue) {
DimensionPickerAction.selectionChange(this.props.dimension, newValue);
}
render() {
var optionNodes = this.state.items.map((item) => {
if (item === this.state.currentItem)
return(<option value="{item}" selected>{item}</option>)
else
return(<option value="{item}">{item}</option>)
});
return(<div><select onchange="onSelectionChange">{optionNodes}</select></div>);
}
}
export default DimensionPicker;
Very surprisingly, I get an error
Warning: getInitialState was defined on DimensionPicker, a plain JavaScript
class. This is only supported for classes created using React.createClass. Did
you mean to define a state property instead?
I find this very confusing because clearly my component derives from React.Component
Eric's comment is correct. You're using ES6 classes, which means that getInitialState is not supported. You'll need to change this:
class DimensionPicker extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], currentItem: '' };
}
getInitialState() {
this.state = {
items: MovieLensAppStore.getAttributes(this.props.dimension),
currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
};
}
to this:
class DimensionPicker extends React.Component {
constructor(props) {
super(props);
this.state = {
items: MovieLensAppStore.getAttributes(props.dimension),
currentItem : MovieLensAppStore.getCurrentAttribute(props.dimension)
};
}
What about this, if you like to save the initial state construction somewhere for later use:
class DimensionPicker extends React.Component {
constructor(props) {
super(props);
this._getInitialState = this._getInitialState.bind(this)
this.state = this._getInitialState();
}
_getInitialState() {
return { items: [], currentItem: '' }
}