无法读取 null 的 属性 'state'

Cannot read property 'state' of null

我有一个输入和一个按钮

<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.handleSentence}></button>

我已经在构造函数中绑定了两个函数。

onChange(e) {this.setState({sentence: e.target.value});}

handleSentence(e) {console.log('string -->',this.state.sentence)}

关于 handleSentence 函数 log returns Cannot read property 'state' of null.

但在 render(let{sentence}=this.state) returns 中是正确的值,而且我在输入

中看到了我输入的内容

这里是构造函数:

class SentenceForm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            sentence: '',
            splitedSentenceArray:[]
        }
        this.onChange = this.onChange.bind(this);
        this.onClick = this.handleSentence.bind(this);
    }

它应该是这样的:

<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.onClick}></button>

您将 handleSentence 方法绑定到 this.onClick。那是错误的。

最佳做法是在绑定时保持函数名称相同。它避免了您的情况下不必要的混淆。您已经用不同的名称完成了 handleSentence 函数的绑定,但仍然用相同的名称调用它,所以在您的情况下,正在调用该函数,但由于它被不同的名称绑定,因此它没有引用正确的上下文,其中存在状态。

class SentenceForm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            sentence: '',
            splitedSentenceArray:[]
        }
        this.onChange = this.onChange.bind(this);
        this.handleSentence = this.handleSentence.bind(this);
    }