javascript - 将 jsx 标记作为返回语句返回时出错:对象不支持属性或方法
问题描述
错误:对象不支持属性或方法“getTractorNumber”
我想要做的是如果为空则返回<Link to ={`/assign-tractor/${user_id}`}> Assign Tractor </Link>
以呈现,否则返回tractor-id
<Link to ={`/tractor-details/${tractorId}`}>{this.tractorNumber}</Link>
如何修复我的代码以使其执行我想要执行的操作?有没有更好的方法来解决这个问题?
注意:我是 React 和 JavaScript 的新手,所以很多语法和语言的细微差别不是很熟悉。请保持答案尽可能基本,以便于消化。
import React, {Link, useState,Component} from 'react'
import axios from 'axios'
import './assignment-table.css';
import {withRouter} from 'react-router-dom';
class AssignmentTable extends Component {
constructor(props){
super(props);
this.state = {
users : [],
isLoggeIn: false,
tractorNumber:"",
orderNumber:""
}
this.getTractorNumber = this.getTractorNumber.bind(this);
}
componentDidMount(){
axios.get(`http://localhost:3000/project/user/drivers`)
.then(response => {
console.log(response.data[0])
this.setState({ users: response.data })
})
.catch( err => console.log(err));
}
async getTractorNumber(tractorId, user_id){
if(tractorId == null || tractorId ==undefined){
return <Link to ={`/assign-tractor/${user_id}`}> Assign Tractor </Link>;
}
else{
axios.get(`http://localhost:3000/project/tractor/${tractorId}`)
.then(response => {
this.setState({ tractorNumber: response.data.tractorNumber })
});
return <Link to ={`/tractor-details/${tractorId}`}>{this.state.tractorNumber}</Link>;
}
}
render(){
let users = this.state.users? this.state.users.map((item, key) => {
return (
<tr>
<td key = {key}>{item.firstName} {item.lastName}</td>
<td>{this.getTractorNumber(item.tractor, item.id)}</td>
</tr>
)
}) : "No Avilable Driver";
return (
<table className="table">
<thead>
<tr>
<th scope="col">Driver Name</th>
<th scope="col">Tractor</th>
<th scope="col">Order</th>
</tr>
</thead>
<tbody>
{users}
</tbody>
</table>
)};
}
export default withRouter (AssignmentTable)
解决方案
我发现您的代码有几个问题:
我相信错误正在发生,因为getTractorNumber
没有正确绑定到this
. 您需要在构造函数中绑定它:
constructor(props) {
...
this.getTractorNumber = this.getTractorNumber.bind(this);
}
另外,调用您的 API 或setState
在render
. 您应该将该部分componentDidMount
与您的其他 API 调用一起移动。
您引用this.tractorNumber
in getTractorNumber
,但该类变量似乎不存在。我想你的意思是this.state.tractorNumber
?
最后,我不知道 React 导出Link
组件。很确定你应该从react-router-dom
.
推荐阅读
- python - 当 lxml etree.ElementTree 是字符串时,为什么 XML 仅针对 XSD 进行验证?
- apache-camel - 对骆驼聚合拆分的最后一个索引执行操作
- php - ::class 方法的使用
- javascript - 为什么我收到错误“firebase.database 不是函数”?
- python - 从不同的字典和键/值集创建多级字典 - python
- python-3.x - 不使用 split() 方法重新排列 String(sentence) 的位置
- graph - 如何在不修改初始图形的情况下克隆图形?
- cryptography - 我需要了解加密货币中的钱包,交易所如何为每个用户生成存款地址?
- charts - ChartJS - 折线图,位置工具提示
- java - 字符串比较,字母顺序