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

Axios React GET request - set state or props from API call?

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

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

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

我想我遗漏了一些明显的东西,但一直找不到。我很确定这不是像 这样的语法错误,或者我没有 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 调用的 return 中放置一个调试器,this 返回为未定义。如果我在 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();

有什么办法可以正确连接这一切吗?

您应该设置 organizations 而不是 org。因为那是您在 ajax 请求后更新的内容。相应地更改 OrgTable 属性。

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

您还需要在拥有数据之前允许使用占位符。或者至少为空。

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