首页 > 解决方案 > 将 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)

标签: javascriptreactjsaxios

解决方案


我发现您的代码有几个问题:

我相信错误正在发生,因为getTractorNumber没有正确绑定到this. 您需要在构造函数中绑定它:

constructor(props) {
  ...
  this.getTractorNumber = this.getTractorNumber.bind(this);
}

另外,调用您的 API 或setStaterender. 您应该将该部分componentDidMount与您的其他 API 调用一起移动。

您引用this.tractorNumberin getTractorNumber,但该类变量似乎不存在。我想你的意思是this.state.tractorNumber

最后,我不知道 React 导出Link组件。很确定你应该从react-router-dom.


推荐阅读