导入模块错误这是未定义的

时间:2017-09-05 08:03:13

标签: javascript reactjs

CounterView.js

import React from 'react';
const  CounterView =   <div>
    <h1>{this.state.counter}</h1>
    <button onClick={this.handleDecrement}>-</button>
    <button onClick={this.handleIncrement}>+</button>
</div>;
export default CounterView;

Counter.js

import React from 'react';
import CounterView from '../ComponentsView/CounterView.js';

class Counter extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            counter: 0,
        }
    }

    render() {
        return (
           < CounterView />
        )
    }

}

我有错误:

  

未捕获的TypeError:无法读取属性&#39; state&#39;未定义的

请帮帮我。 抱歉,我有第二个受欢迎的问题:为什么我必须要求

  import React from 'react';

在我的应用程序的每个文件中?他第一次打电话只需要一个?

1 个答案:

答案 0 :(得分:1)

相应地更改您的代码。您无法从子组件到达其他组件状态。您可以使用道具而不是州。

<强> CounterView.js

import React from 'react';
class CounterView extends React.Component{ 
    render() {
        return (
            <div>
                <h1>{this.props.counter}</h1>
                <button onClick={this.props.handleDecrement}>-</button>
                <button onClick={this.props.handleIncrement}>+</button>
            </div>
        );
    }
}
export default CounterView;

<强> Counter.js

import React from 'react';
import CounterView from '../ComponentsView/CounterView.js';

class Counter extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            counter: 0,
        }
    }
    handleDecrement() {
      // do the decrements here
    }
    handleIncrement() {
      // do the increments here
    }
    render() {
        return (
           <CounterView counter={this.state.counter} handleDecrement={this.handleDecrement.bind(this)} handleIncrement={this.handleIncrement.bind(this)}  />
        )
    } 
}