【问题标题】:implementation of search functionality in reactjsreactjs中搜索功能的实现
【发布时间】:2021-04-17 10:41:59
【问题描述】:

我正在尝试在 reactjs 中实现搜索功能。我不知道该怎么做。下面我给出了我尝试过的代码。
我需要在 serach 之后在表格中显示结果。

                        render() { 
                            return (
                                <div>
                                    <input onChange={this.handleSearchChange} placeholder="Search"/>
                                </div>  
                                )
                        }

//下面是我的函数

            handleSearchChange = e => {
                const { value } = e.target;
                var self = this 
            axios.post("http://localhost:4000/get",  { name:   value })
                .then(function(res){
                    console.log("detail",res.data)
                })
                .catch(function(err){
                    console.log('Error',err)
                })  
            };

//下面是我的api响应

              [
            {color: "green",name: "test",age: "22"},
            {color: "red",name: "test2",age: "23"}
        ]

【问题讨论】:

  • 你检查js-search了吗?
  • 究竟是什么不工作?您的请求有效吗?
  • 是的,请求工作正常,我得到了响应。我已经提到了上面的回应。

标签: javascript node.js reactjs search drop-down-menu


【解决方案1】:

获得数据后,您需要将其添加到状态中,以便在状态更改时可以迭代数据并重新呈现视图。我在这个例子中使用了 React 钩子。希望对大家有所帮助。

table { 
  background-color: white;
  border-collapse: collapse;
}

tr:nth-child(even) {
  background-color: #efefef;
}

td {
  padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script type="text/babel">

  // Grab the hooks you need
  const { useState, useEffect } = React;

  // The main function that will loop over the data
  // and create the rows for the table
  function createRows(data) {

    // Iterate over the data and for each object
    // return a new HTML row
    return data.map((row, i) => {
      const { color, name, age } = row;
      return (
        <tr key={i}>
          <td>{color}</td>
          <td>{name}</td>
          <td>{age}</td>
        </tr>
      )
    });
  }

  // Mock API call which returns data after a 2 second delay
  function fakeAPICall() {
    return new Promise((res, rej) => {
      setTimeout(() => {
        res('[{"color": "green","name": "test","age": "22"},{"color": "red","name": "test2","age": "23"}]');
      }, 2000);
    });
  }

  function Example () {

    // Set up the state in the componenent
    const [data, setData] = useState([]);

    // When the component renders load in the data
    // and set that as your state.
    useEffect(() => {
      async function getData() {
        const response = await fakeAPICall();
        const data = JSON.parse(response);
        setData(data);
      }
      getData();
    }, []);

    // If there's no data in state display nothing...
    if (!data.length) return <div>No data</div>

    // ...otherwise pass the data into the createRows function
    // and return them the row data
    return (
      <table>
        <thead>
          <th>Color</th>
          <th>Name</th>
          <th>Age</th>
        </thead>
        <tbody>
          {createRows(data)}
        </tbody>
      </table>
    )
  };

  // Render it
  ReactDOM.render(
    <Example />,
    document.getElementById("react")
  );

</script>
<div id="react"></div>  

下面是我使用类组件的方法:

    table { 
      background-color: white;
      border-collapse: collapse;
    }

    tr:nth-child(even) {
      background-color: #efefef;
    }

    td {
      padding: 1em;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script type="text/babel">

  // The main function that will loop over the data
  // and create the rows for the table
  function createRows(data) {

    // Iterate over the data and for each object
    // return a new HTML row
    return data.map((row, i) => {
      const { color, name, age } = row;
      return (
        <tr key={i}>
          <td>{color}</td>
          <td>{name}</td>
          <td>{age}</td>
        </tr>
      )
    });
  }

  // Mock API call which returns data after a 2 second delay
  function fakeAPICall() {
    return new Promise((res, rej) => {
      setTimeout(() => {
        res('[{"color": "green","name": "test","age": "22"},{"color": "red","name": "test2","age": "23"}]');
      }, 2000);
    });
  }

  class Example extends React.Component {

    // Set up the state in the componenent
    constructor() {
      super();
      this.state = { data: [] };
    }

    // When the component renders load in the data
    // and set that as your state.
    componentDidMount() {
      fakeAPICall().then(response => {
        return JSON.parse(response);
      }).then(data => {
        this.setState({ data });
      });
    }

    // ...otherwise pass the data into the createRows function
    // and return them the row data
    render() {
      if (!this.state.data.length) return <div/>
      return (
        <table>
          <thead>
            <th>Color</th>
            <th>Name</th>
            <th>Age</th>
          </thead>
          <tbody>
            {createRows(this.state.data)}
          </tbody>
        </table>
      )
    }
    }

  // Render it
  ReactDOM.render(
    <Example />,
    document.getElementById("react")
  );

</script>
<div id="react"></div>

【讨论】:

  • 我是 reactjs 新手 .. 我正在使用类组件来呈现表格。它给出的错误。我怎样才能把它写到我的类组件中
  • @kp987987,我已经用类组件示例更新了我的答案。
【解决方案2】:

如果我正确理解您的问题,您正在尝试更新您的表格渲染。正如您所提到的,我会假设您的 API 在通话中运行良好。

在 React 中有一个叫做“状态”的特性,它可以保存一个可变的状态。很酷的一点是,当您更改该状态时,您的组件会重新渲染。一点解释还是 ReactJS 状态:

// intialization of a variable "varX" of type integer with value 1
// setVarX(int) is used to change the variable state
const [varX, setVarX] = React.useState(1);

// changing the state
setVarX(3);

因此,对于您的问题,我们需要两件事:保存 API 响应并在 API 有新数据时更新的状态,以及您的数据的表格显示。

在你正在渲染的函数中(我假设它是名称 TableView),让我们添加这个状态并在 API 成功时在处理程序中更新它

function TableView(){

     // table data, initialized to empty array
     const [tableData, setTableData] = React.useState([]);

     // handle updated with set state
     handleSearchChange = e => {
        const { value } = e.target;
        var self = this.axios.post("http://localhost:4000/get",  { name:   value })
        .then(function(res){
            console.log("detail",res.data)
            setTableData(res.data) // update the table data!
        })
        .catch(function(err){
            console.log('Error',err)
        })  
    };
     
    return (...) // render function in the next section
}

渲染

该函数将使用react的地图功能:

render() { 
    return (
        <div>
            <input onChange={this.handleSearchChange} placeholder="Search"/>
            <table style="width:100%">
              <tr>
                <th>Color</th>
                <th>Name</th> 
                <th>Age</th>
              </tr>
            </table>
            {
                tableData.map((entry, index) => 
                    <tr index={index}>
                        <td>{entry.color}</td>
                        <td>{entry.name}</td> 
                        <td>{entry.age}</td>
                    </tr>
                )
            }
        </div>  
    )
}

PS:我不是最擅长 JSX,请随意编辑和增强渲染部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2019-12-21
    • 2019-02-20
    • 2021-01-08
    相关资源
    最近更新 更多