反应主页上的搜索栏以重定向到结果页面

问题描述 投票:0回答:1

我正在尝试在网站主页上创建一个搜索栏以重定向到搜索页面并显示结果,但用户可以从那里继续搜索。所以类似于google的功能,我们第一次进入的时候只有一个搜索栏,一旦我们搜索了,我们就可以从显示结果的页面继续搜索。这是我当前的代码,我不知道如何实现此功能。

import React from "react";
import "./home.css";
import {Link} from "react-router-dom";
import SearchField from 'react-search-field';
import { Redirect } from 'react-router'
import axios from 'axios';


export default class Home extends React.Component {
    state = {
        searchResults: [],
        search: '',
        
    }
    constructor(props) {
        super(props);
        this.onSearchClick= this.onSearchClick.bind(this);
    }
    render() {
        return (
            <div class="container-fluid">
                <div class = "row body flex-nowrap">
                    <div class="bg-image">
                    </div>
                    <div class="bg-text">
                        <div class="title" >
                        Oerinspanish <br/>
                        </div>
                        Recursos educativos de acceso libre <br/>
                        para la enseñanza del español <br/> <br/> <br/>
                        
                        <SearchField class="search" placeholder= 'búsqueda' input type= "text" required value={this.state.input} 
                            onSearchClick={this.onSearchClick}>
                            <Redirect to={{
                                pathname: '/search',
                                state: { searchResults: this.state.searchResults }
                            }}/>
                        </SearchField>
                    </div>
                </div>
            </div>
        );
    }
    onSearchClick(event) {
        let url = 'http://localhost:3000/search' + encodeURI(this.state.search) + '&json=1';
        axios.get(url)
        .then(response => {
            let data = {
            searchResults: response.data,
            };
            this.setState(data);
        })
        .catch(error => console.log(error));
    }
}

reactjs react-router-dom searchbar
1个回答
0
投票

导航应该在

onSearchClick
成功解析时响应 GET 请求来完成,而不是在选择输入的中间完成。命令式(与声明式)位是关于显式地发出命令,即调用函数来执行事情,而不是将其推迟到其他代码。

建议:

不要理会本地组件

searchResults
状态。一旦 GET 请求得到解决并且您在响应中获得了搜索结果,请通过
history
对象发出到目标路由的重定向,并将结果存储在路由状态中。

onSearchClick(event) {
  const { search } = this.state;
  const url = 'http://localhost:3000/search' + encodeURI(search) + '&json=1';
  axios.get(url)
    .then(response => {
      this.history.replace({
        pathname: "/search",
        state: {
          searchResults: response.data,
        },
      });
    })
    .catch(console.error);
}

...

<SearchField
  class="search"
  placeholder="búsqueda"
  input
  type="text"
  required
  value={this.state.input} 
  onSearchClick={this.onSearchClick}
/>

这需要类组件接收 route props,以便它可以访问

this.history
。为此,该组件要么需要由
Route
组件直接渲染,要么包装在 withRouter HOC 中以将它们注入并可用。

© www.soinside.com 2019 - 2024. All rights reserved.