Javascript &引用;这";axios捕捉块中未定义箭头函数
我得到了一个错误: 元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义 使用此代码:Javascript &引用;这";axios捕捉块中未定义箭头函数,javascript,reactjs,Javascript,Reactjs,我得到了一个错误: 元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义 使用此代码: class Registration extends React.Component { state = {...} submitRegistration = e => { let registration = {...} Axios.post('/registration', registration) .then(r
class Registration extends React.Component {
state = {...}
submitRegistration = e => {
let registration = {...}
Axios.post('/registration', registration)
.then(res => {
console.log("Successfully sent registration data", res)
})
.catch(() => {
this.setState({ showNoServerConnectionAlert: true })
});
}
e.preventDefault()
}
render() {
return (
...
)
}
export default Registration;
问题是,尽管我使用的是箭头函数,但由于某种原因,“this”不能在catch块中引用。我也尝试过绑定“this”,但也没用。有人有想法吗?因为每个代码块中的“this”可能有不同的方法,并引用其他父级。
为了解决这个问题,您必须在全局范围内定义一个变量,并使其等于此值。然后在代码的其余部分中,该变量可能是可访问的
class Registration extends React.Component {
state = {...}
submitRegistration = e => {
let registration = {...}
var sellf = this;
Axios.post('/registration', registration)
.then(res => {
console.log("Successfully sent registration data", res)
})
.catch(() => {
sellf.setState({ showNoServerConnectionAlert: true })
});
}
e.preventDefault()
}
render() {
return (
...
)
}
export default Registration;
您提到的错误消息可能是渲染方法有问题。你能告诉我们渲染方法吗?哇,谢谢你的提示解决了这个问题。问题是,当catch块中的“showNoServerConnectionAlert”设置为true时,我有条件地呈现了一个组件,但该组件本身未定义。react错误消息让我有点困惑。代码片段中的左括号和右括号也不匹配。在请求帮助时提供一个函数确实很重要。不,箭头函数构造为您提供了这一功能。这也不起作用,因为现在
self
将是(仍然)的this
箭头函数submitRegistration
仍然是错误的this
。我认为这会导致错误,因为您无法在类
正文中定义var
。