简体   繁体   English

在 reactjs 中实现搜索功能

[英]implementation of search functionality in reactjs

I am trying to implement search functionality in reactjs.我正在尝试在 reactjs 中实现搜索功能。 i am not getting how to do.我不知道该怎么做。 below i have given code which i have tried.下面我给出了我尝试过的代码。
i need to display result in table after serach.我需要在搜索后在表格中显示结果。

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

// below is my function // 下面是我的 function

            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)
                })  
            };

//below is my api response //下面是我的 api 响应

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

Once you have the data you need to add it to state so that when the state changes you can iterate over the data and rerender the view.获得数据后,您需要将其添加到 state 以便当 state 更改时,您可以遍历数据并重新渲染视图。 I'm using React hooks in this example.我在这个例子中使用了 React 钩子。 I hope it helps a little.我希望它有一点帮助。

 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>

And here's how I would do it with a class component:以下是我将如何使用 class 组件进行操作:

 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>

If I understand your question correctly, you are trying to update your table rendering.如果我正确理解您的问题,您正在尝试更新您的表格渲染。 I will assume, as you mentioned, that your API is working fine at the call.正如您所提到的,我将假设您的 API 在通话中工作正常。

In React, there is a feature called "state", which can preserve a variable state.在 React 中有一个叫做“状态”的特性,它可以保存一个变量 state。 The cool thing about it also is that when you change that state, your component re-renders.很酷的一点是,当您更改 state 时,您的组件会重新渲染。 A little explanation or ReactJS states:一点解释或 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);

So for your problem, we need two things: a state that holds the API response and that we update whenever the API has new data, and a table display of your data.因此,对于您的问题,我们需要两件事:一个 state 保存 API 响应,并且每当 API 有新数据时我们都会更新,以及您的数据的表格显示。

State State

In your function that is rendering (I assume it is name TableView), let's add this state and have it updated in the handler when the API succeeds在您正在呈现的 function 中(我假设它是名称 TableView),让我们添加这个 state 并在 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
}

Render使成为

The function would use the map feature of react: function 将使用反应的 map 功能:

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: I am not the best at JSX feel free to edit and enhance the render section PS:我不是 JSX 最好的,可以随意编辑和增强渲染部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM