首页 > 解决方案 > TypeError:无法读取未定义的属性“绑定”,我不知道这意味着什么。反应js

问题描述

我在尝试运行我的 React 代码时遇到了这个错误,发现这是一个常见错误,但是在查看了其他人的问题后,我仍然遇到了如何解决这个问题的问题。我还是 React 的新手,所以我有点迷路了。代码应该做的是获取一个 JSON 文件并将其显示为表格,然后按钮应该按姓氏对其进行排序并重新显示表格。

import data from './data.json' //Imports the JSON from local file, can be changed later to pull from api
import {Button, View} from 'react-native';

export default function App() {

    return (
       <PaientTable/>
        
      );
}





class PaientTable extends React.Component { 
        

    constructor(props) {
        super(props);
        
        this.state = { counter: 0 };
       // this.sort = this.sort.bind(this);
      }
    
    
    render(){

        

       function sort (){ 
            return this.setState( 
  
              data.sort((a, b) => {//sorts by name
                  if (a.lName < b.lName) {
                    return -1;
                  }
                  if (a.lName > b.lName) {
                    return 1;
                  }
                  return 0;
                })
            );
        }
    return (

        
        
<table>
        <caption>Paients</caption>
        <thead>
          <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>
            <button type="button" onClick={() => this.sort.bind(this)}> 
              Last Name
            </button>
          </th>
            
          </tr>
        </thead>
        <tbody>
          {data.map(paient => (
            <tr>
              <td>{paient.id}</td>
              <td>{paient.fName}</td>
              <td>{paient.lName}</td>
            </tr>
          ))}
        </tbody>
      </table>
        
        
    
    );
          }
  }

标签: javascriptreactjsreact-native

解决方案


您已将其定义sort为 内部的局部变量render,但是您尝试访问它的所有地方都将其视为该类的成员。所以不要像这样构造它:

class PaientTable extends React.Component { 
 // ...
 render() {
    function sort () {
       // ...
    }
    // ...
 }
}

做这个:

class PaientTable extends React.Component { 
  // ...
  sort() {
    // ...
  }

  render() {
    // ...
  }
}

推荐阅读