简体   繁体   中英

React Cannot read property of null

I am making a ReactJS Application which is throwing an error on the state property num and I am not quite sure why as it appears to be properly initialized and used. The error occurs on it's first usage on line 126 and reads: cannot read property 'num' of null , which indicates to me that it would be an issue with the class state. Where is the mistake?

import React, { Component } from 'react';
import ReactDom from 'react-dom';
import { Parallax, Background } from 'react-parallax';
import { Form, FormControl, FormGroup, Checkbox, ControlLabel, Col, Row, Grid, DropdownButton, Jumbotron, MenuItem, Button, ButtonToolbar, Well, Navbar, NavItem, NavDropdown, Nav } from 'react-bootstrap';
import imgs from './ImgFactory.js';
import "animate.css/animate.min.css";
import ScrollAnimation from 'react-animate-on-scroll';
import Plot from 'react-function-plot';
import {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, PieChart, Pie, ResponsiveContainer, AreaChart, Area, ReferenceLine, Cell, BarChart, Bar, LabelList} from 'recharts';
import Typing from 'react-typing-animation';
import TypeWriter from 'react-typewriter';
import Moment from 'react-moment';
import getWeb3 from './utils/getWeb3.js';
import { Web3Provider } from 'react-web3';
import {Helmet} from "react-helmet";
// Using an ES6 transpiler like Babel
import Slider from 'react-rangeslider'

// To include the default styles
import 'react-rangeslider/lib/index.css'
import './EthApp.css';


class EthApp extends Component {

  constructor(props) {
    super(props);

    this.setState({
      web3: null,
      num: 0
    })
    this.handleOnChange = this.handleOnChange.bind(this);
  }

  componentWillMount() {
    // Get network provider and web3 instance.
    // See utils/getWeb3 for more info.
    getWeb3
    .then(results => {
      this.setState({
        web3: results.web3
      })
      // Get accounts.
      results.web3.eth.getAccounts((error, accounts) => {
        if (error == null) {
          this.setState ({
            acc: accounts[0],
            num: 0
          });
          let displayed = "ETH Address: " + accounts[0];
          ReactDom.render(displayed, document.getElementById('ETH_ADDR'));
          // Instantiate contract once web3 provided.
          this.instantiateContract(results, accounts);
        }
      })


    })
    .catch(() => {
      console.log('Error finding web3.')
    })
  }

  instantiateContract(results, accounts) {

    var contract_address = "0x29a9c0904f2e41ac87a0cc651df0efd4303051bc";
    var contract_abi = [ { "constant": false, "inputs": [ { "name": "to", "type": "address" }, { "name": "amount", "type": "uint256" } ], "name": "sendTokens", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "_address", "type": "address" } ], "name": "checkBalance", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getCentralBankBalance", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "amount", "type": "uint256" } ], "name": "requestFromMint", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "name": "circulatingSupply", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "constructor" } ];
    var contract_instance = new results.web3.eth.Contract(contract_abi, contract_address);
    contract_instance.methods.checkBalance(accounts[0]).call({from: accounts[0]}, function(error, result){
        alert("Balance: " + result);
    });
  }

  handleOnChange = (value) => {
      this.setState({
        num: value
      })
  }

  render() {

    return (
      <div className="EthApp">
        <Web3Provider>
        <Helmet bodyAttributes={{style: 'background : linear-gradient(to top, #3494E6 , #EC6EAD); background-repeat: no-repeat;'}}/>
        <div className='mainView' style={{height: 2000}}>
          <br></br><br></br><br></br><br></br><br></br>
          <TypeWriter typing={0.3} style={{margin: '10px'}}>
            <span style={{font: '60px courier', color: 'black'}}>This is the 3rd Web...</span>
          </TypeWriter>
          <br></br>
          <br></br>
        <Form horizontal style={{width: '90%', marginLeft: 5}}>
        <FormGroup controlId="formHorizontalEmail">
          <Col componentClass={ControlLabel} sm={2}>
            Email
          </Col>
          <Col sm={10}>
            <FormControl type="email" placeholder="Email" />
          </Col>
        </FormGroup>

        <FormGroup controlId="formHorizontalPassword">
          <Col componentClass={ControlLabel} sm={2}>
            Password
          </Col>
          <Col sm={10}>
            <FormControl type="password" placeholder="Password" />
          </Col>
        </FormGroup>

        <FormGroup>
          <Col smOffset={2} sm={10}>
            <Checkbox>Remember me</Checkbox>
          </Col>
        </FormGroup>

        <FormGroup>
          <Col smOffset={2} sm={10}>
            <Button type="submit">Sign in</Button>
          </Col>
        </FormGroup>
      </Form>
      <Slider
        value={this.state.num}        /// <--- ERROR
        onChange={this.handleOnChange}
      />
        </div>
      </Web3Provider>
      </div>
    );
  }
}



export default EthApp;

In a constructor, it's enough just to assign the state:

this.state = {
  web3: null,
  num: 0
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM