首页 文章

Axios React GET请求 - 从API调用设置状态或道具?

提问于
浏览
0

React的新功能 - 我想通过Axios向我的Rails后端发出GET请求,以引入组织列表中的静态数据(只是用户具有搜索功能的表) .

目前,我按照我想要的方式工作,同时传递我手工制作的一系列组织,作为我的 WholeApp 类的道具 . 现在,我想调用API endpoints 来实现相同的效果,但是要使用真实数据 .

但是,当我通过Axios调用将状态设置为组织列表时,我认为它会在调用完成之前尝试呈现组件,并且在OrgTable类(构建表)中出现未定义的错误 .

我想我错过了一些明显的东西,但却找不到它 . 我很确定它不是像this那样的语法错误,或者说如果没有ES6 sytnax我没有正确绑定 .

这是我进行Axios调用的地方:

class WholeApp extends Component {
  constructor(props) {
    super(props);

    this.state = {
      filterText: '',
      organizations: []
    };
    this.handleFilterTextInput = this.handleFilterTextInput.bind(this);
  }

  handleFilterTextInput(filterText) {
    this.setState({
      filterText: filterText
    });
  }

  componentDidMount() {
    axios.get('http://localhost:3000/api/v1/organizations').then((result) => {
      this.setState({ organizations: result.data });
    });
  }

  render () {
    return (
      <div>
        <TableInfoText />
        <SearchBar
          filterText={this.state.filterText}
          onFilterTextInput={this.handleFilterTextInput}
        />
        <OrgTable
          // orgs={this.props.orgs}
          orgs={this.state.orgs}
          filterText={this.state.filterText}/>
      </div>
    );
  }
}

另外,如果我在 axios.get 调用的返回中放置一个调试器, this 将返回undefined . 如果我在OrgTable上使用this.props.orgs,它可以正常工作(使用我手工制作的组织) . 使用 this.state.orgs 的未注释部分在遇到forEach时会抛出错误:

class OrgTable extends Component {
  render () {
    const rows = [];

    this.props.orgs.forEach((org) => {
      if ((org.name + org.city + org.county + org.state + org.zip).toLowerCase().indexOf(this.props.filterText) === -1) {
        return;
      }
      rows.push(<OrgRow org={org} key={org.name}/> );
    });

    return(
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>City</th>
            <th>County</th>
            <th>State</th>
            <th>ZIP</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  }
}

我通过以下方式从另一个文件渲染整个文件:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import WholeApp from './App';
import {organizations} from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
  <WholeApp orgs={organizations} />,
  document.getElementById('root')
);
registerServiceWorker();

Any ideas how I can get this all wired up correctly?

1 回答

  • 3

    你应该设置 organizations 而不是 org . 因为这是你在ajax请求之后更新的内容 . 相应地更改OrgTable属性 .

    <OrgTable
        orgs={this.state.organizations}
        filterText={this.state.filterText}/>
    

    在获得数据之前,您还希望允许占位符 . 或者至少为null .

    { this.state.organizations && <OrgTable
          orgs={this.state.organizations}
          filterText={this.state.filterText}/> }
    

相关问题