首页 > 解决方案 > 在 React Row 中获取动态创建的表数据

问题描述

我对 NodeJs 比对反应更熟悉。我已经构建了一个反应组件,用于搜索用户输入并根据用户在搜索输入表单中输入的值以表格格式提供输出。这是我想要的工作,模块的代码如下:

import React, { Component } from 'react';
import axios from 'axios';
import Suggestions from './Suggestions';

// API url
const API_URL = 'http://localhost:3000/api/file_infos'

class Search extends Component {
  state = {
    query: '',
    results: []
  }
  getCount = () => {
    axios.get(`${API_URL}count?filter[where][id][regexp]=/${this.state.query}/i`)
      .then(count => {
        this.setState({
          results: count.data
        })
      })
  }

  // query loop back API for matching queries base on text input
  getInfo = () => {
    axios.get(`${API_URL}?filter[where][id][regexp]=/${this.state.query}/i&filter[limit]=20`)
      .then(response => {
        this.setState({
          results: response.data
        })
      })
  }
  // check to see if input on the search bar has changed and update the search query accordingly 
  handleInputChange = () => {
    this.setState({
      query: this.search.value
    }, () => {
      if (this.state.query && this.state.query.length > 1) {
        if (this.state.query) {
          this.getInfo()
        }
      } else if (!this.state.query) {
      }
    })
  }
  // render form and pass results back to the home component 
  render() {
    return (
      <div>
      <form>
        <input
          placeholder="Search for..."
          ref={input => this.search = input}
          onChange={this.handleInputChange}
        />

      </form>

      <Suggestions results={this.state.results} />
      </div>
    )
  }
}

export default Search

第二个模块是以表格格式显示输出的建议模块。

我正在构建的应用程序的下一部分将根据用户选择的表格行打开一个文件。我希望将该表数据返回给一个函数,以便我可以向我的 API 发出一个 http post 请求,然后使用 NodeJS 模块打开该文件。

我希望建议组件返回表格单元格中数据项的值,以便可以使用数据发送到 API 以打开我的文件。到目前为止我提出的代码只返回一个未定义的错误。

以下是我目前拥有的:

import React from 'react';
// return results in a table format based on the text input entered 
 const Suggestions = (props) => {

   const state = {
        results: []
    }

    const handleFormOpen = () => {
        this.setState({
            results: this.results.value
        },
        console.log(this.state.results)
        )
    }

    const options = props.results.map(r => (
        <tr key={r.id} ref={tr => this.results = tr} onClick={handleFormOpen.bind(this)}>
            <td>{r.id}</td>
            <td>{r.OriginalPath}</td>
            <td>{r.CreateDate}</td>
            <td>{r.AccessDate}</td>
            <td>{r.WriteDate}</td>
            <td><i className="fas fa-book-open"></i></td>
        </tr>
    ))
    return <table className="striped responsive-table">
        <thead>
            <tr>
                <th>File Name</th>
                <th>Parent Directory</th>
                <th>Creation Date</th>
                <th>Access Date</th>
                <th>Write Date</th>
                <th>Open File</th>
            </tr>
        </thead>
        <tbody>
            {options}
        </tbody>
    </table>
}

export default Suggestions;

如果我试图以正确的方式解决这个问题,我现在真的不确定。我在想也许建议组件可能需要变成一个完整的类扩展组件,但在这一点上我相当迷茫。有人可以指出我的愚蠢并让我朝着正确的方向前进吗?

更新

正如评论中所要求的,这里是我浏览器的错误日志:

Suggestions.js:10 Uncaught TypeError: Cannot read property 'results' of undefined
    at Object.handleFormOpen (Suggestions.js:10)
    at HTMLUnknownElement.callCallback (react-dom.development.js:145)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:195)
    at invokeGuardedCallback (react-dom.development.js:248)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:262)
    at executeDispatch (react-dom.development.js:593)
    at executeDispatchesInOrder (react-dom.development.js:615)
    at executeDispatchesAndRelease (react-dom.development.js:713)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:724)
    at forEachAccumulated (react-dom.development.js:694)
    at runEventsInBatch (react-dom.development.js:855)
    at runExtractedEventsInBatch (react-dom.development.js:864)
    at handleTopLevel (react-dom.development.js:4857)
    at batchedUpdates$1 (react-dom.development.js:17498)
    at batchedUpdates (react-dom.development.js:2189)
    at dispatchEvent (react-dom.development.js:4936)
    at interactiveUpdates$1 (react-dom.development.js:17553)
    at interactiveUpdates (react-dom.development.js:2208)
    at dispatchInteractiveEvent (react-dom.development.js:4913)

标签: node.jsreactjshtml-table

解决方案


第一件事由于您的Suggestions组件使用状态,我建议您使用 statefull 组件。

Stateless component用于获取 props 和返回 jsx 元素,无状态组件中不会有任何状态突变。这被称为pure function in javascript。希望这清楚。

此外,由于您声明handleFormOpen为箭头函数,因此您无需进行绑定。绑定由箭头函数自动处理。如果您不想使用箭头函数并且想要绑定它,那么始终只在构造函数中进行绑定,但不要像在 map 中那样在组件中的任何位置进行绑定。

PFB 校正Suggestions组件代码

import React, { Component } from 'react';
// return results in a table format based on the text input entered 
 export default class Suggestions extends Component {
  constructor(props){
    super(props);
    this.state = {
      results: [],
      value: ""
    }
  }


  handleFormOpen = (path, id) => {
    console.log("id", id, path);//like wise pass value to this function in .map and get the value here
      this.setState({
          value: id
      });
  }


    render(){ 
      const { results } = this.props;
      return (<div>
        <table className="striped responsive-table">
          <thead>
              <tr>
                  <th>File Name</th>
                  <th>Parent Directory</th>
                  <th>Creation Date</th>
                  <th>Access Date</th>
                  <th>Write Date</th>
                  <th>Open File</th>
              </tr>
          </thead>
          <tbody>
              {Array.isArray(results) && results.length > 0 && results.map(r => (
                <tr key={r.id} ref={tr => this.results = tr} onClick={() => this.handleFormOpen(r.OriginalPath, r.id)}>
                    <td>{r.id}</td>
                    <td>{r.OriginalPath}</td>
                    <td>{r.CreateDate}</td>
                    <td>{r.AccessDate}</td>
                    <td>{r.WriteDate}</td>
                    <td><i className="fas fa-book-open"></i></td>
                </tr>
              ))}
          </tbody>
        </table>
      </div>)
    }    
}

export default Suggestions;

推荐阅读