【发布时间】:2018-11-11 13:48:47
【问题描述】:
我知道这个问题被问了很多,我确实检查了提供的大多数其他答案,但我仍然不知道为什么会出现这个错误。
情况:
我有我的textinput 类,其中我有一个简单的表单供用户输入名称。当用户提交按钮时,会调用我的后端的 REST 调用,并且 UI 应显示用户名。
我已经覆盖了我的App 类的函数componentDidMount,以便在页面加载时对我的后端进行初始调用。此调用有效,我从后端得到正确答案,并且 UI 得到更新。
但是当我从 TextInput 班级拨打电话时,我收到错误消息:
this2.setState 不是函数
我相信发生这种情况是因为我从另一个类调用该函数,而 this state 设置不正确。我试图绑定所有的东西,但这并没有改变任何东西。如果有人知道我做错了什么,那将非常有帮助!
我有以下课程:
import React, { Component } from 'react';
import logo from './logo.svg';
import Greeting from './components/greeting';
import TextInput from './components/textInput';
import './App.css';
const axios = require('axios');
class App extends Component {
constructor(props) {
super(props);
this.state = {name: "World"};
this.getFormattedNameFromBackend.bind(this);
this.setState.bind(this);
}
componentDidMount() {
this.getFormattedNameFromBackend(this.state.name);
}
getFormattedNameFromBackend(name) {
axios({
method:'get',
url:'http://localhost:8080/hello?name=' + name
}).then((response) => {
this.setState({ name : response.data.name});
}).catch(function(error){
console.log(error);
});
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<Greeting data={this.state}/>
<TextInput callBack = {this.getFormattedNameFromBackend}/>
</header>
</div>
);
}
}
export default App;
这是我在 axios rest 调用中得到错误的主类。
第二类是这样的:
import React, { Component } from 'react';
export default class TextInput extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
this.props.callBack(this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit= {this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
所以问题是,我如何在 getFormattedNameFromBackend 方法中调用正确的 this?
已解决:
错误是设置 Textinputfield 的 props 错误。正确的应该是
<TextInput callBack = {(name)=>this.getFormattedNameFromBackend(name)}/>
【问题讨论】:
-
听起来
this引用了错误的对象。尝试打印this是它引发的位置,或阅读此stackoverflow.com/questions/45041878/closures-in-react 简而言之,渲染函数中的事件作用于event对象而不是定义渲染函数的类,这是因为事件是异步的。 .. -
当时我收到错误“this”是文本输入类型的对象。但是我该如何改变呢?
-
尝试查看我提供的链接,最简单的方法是通过闭包
onSubmit= (e) => {this.handleSubmit(e)}绑定它。也看看这个:reactjs.org/docs/handling-events.html -
我正在尝试这个,但这实际上给了我语法错误。 :/ 我现在正在尝试这个:onSubmit={(e)=>this.handleSubmit(e)} 但这给了我之前遇到的相同错误
-
看看这个,它似乎在工作jsfiddle.net/n5u2wwjg/233958
标签: javascript reactjs axios