0

I am pretty new to React, what I want to do is periodically generate several numbers and update the view:

<script type="text/jsx">
      var ChartFrame = React.createClass({
        datagenerator: function(n, itvl){
          function randomD(){
            data2fill = [];
            for(var i=0; i<n; i++){
              data.push(Math.random()*10);
            }
            this.setState({
              "data": data
            });
          }
          var counter = setInterval(randomD, itvl);
          return counter;
        },
        getInitialState: function(){
          return {
            data:(function(){  
              this.state.counter = this.datagenerator(5, 1000); 
              return [];  
            })()
          }
        },
        render:  function(){
          var ds = this.state.data;
          var divs = ds.map(function(d, i){
            return <div>   d   </div>;
          });
          return (
            {divs}
          );
        }
      });
      React.render(<ChartFrame />, document.body);
<script>

However, I get the error message below:

Uncaught TypeError: this.datagenerator is not a function

I wonder what is the correct way to define function in JSX?

1 Answer 1

2

The way you've declared your function is correct but your entire getInitialState is messed up, yo.

What would be the desired behavior here? Since you've declared a new function it will not have access to the correct this which would be the component unless you .bind() it. Unsure what it does or how it works, read this great article. The code is below

return {
    data:(function(){  
        this.state.counter = this.datagenerator(5, 1000); 
        return [];  
    }.bind(this))()
}

However doing that will produce another error for you, this.state is undefined hence you will not be able to set counter on this.state.

this.state is never set in getInitialState since the job of the function is to produce the state. Also you're returning an empty array to the data which will lead to this.state.data be an empty Array.

Furthermore, you might want to start your datagenerator function within the life cycle method #componentDidMount in order for state to have been set and the first render has occurred.

And as a complimentary treat, your code in action!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.