You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React首页搜索栏跳转搜索结果页并支持后续搜索的实现问题

功能实现方案

现有代码问题

  • Redirect组件直接嵌套在SearchField内,页面加载就会自动触发跳转,不符合搜索后才跳转的逻辑
  • 未同步搜索框输入内容到state的search字段,请求接口时无法拿到正确的搜索关键词
  • 接口URL拼接错误,缺少查询参数前缀?q=,请求无法正确传递参数
  • 跳转逻辑未和接口请求成功的时机绑定,无法保证跳转后能拿到搜索结果
  • React语法中应当使用className替代原生的class属性,避免控制台警告

首页(Home组件)修改后代码

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

export default class Home extends React.Component {
    state = {
        searchResults: [],
        search: '',
        shouldRedirect: false // 控制跳转时机的状态
    }
    constructor(props) {
        super(props);
        this.onSearchClick= this.onSearchClick.bind(this);
        this.onSearchChange = this.onSearchChange.bind(this);
    }

    // 同步搜索框输入内容到state
    onSearchChange(value) {
        this.setState({
            search: value
        })
    }

    onSearchClick() {
        // 修正接口URL拼接逻辑,补全查询参数前缀
        let url = 'http://localhost:3000/search?q=' + encodeURI(this.state.search) + '&json=1';
        axios.get(url)
        .then(response => {
            this.setState({
                searchResults: response.data,
                shouldRedirect: true // 接口请求成功后再触发跳转
            });
        })
        .catch(error => console.log(error));
    }

    render() {
        // 满足跳转条件时执行跳转,同时传递搜索结果和搜索词
        if (this.state.shouldRedirect) {
            return <Redirect to={{
                pathname: '/search',
                state: { 
                    searchResults: this.state.searchResults,
                    searchKeyword: this.state.search
                }
            }}/>
        }

        return (
            <div className="container-fluid">
                <div className = "row body flex-nowrap">
                    <div className="bg-image">
                    </div>
                    <div className="bg-text">
                        <div className="title" >
                        Oerinspanish <br/>
                        </div>
                        Recursos educativos de acceso libre <br/>
                        para la enseñanza del español <br/> <br/> <br/>
                        
                        <SearchField 
                            className="search" 
                            placeholder='búsqueda' 
                            type="text" 
                            required 
                            value={this.state.search} 
                            onChange={this.onSearchChange}
                            onSearchClick={this.onSearchClick}
                        />
                    </div>
                </div>
            </div>
        );
    }
}

搜索结果页(Search组件)实现代码

import React from "react";
import SearchField from 'react-search-field';
import axios from 'axios';

export default class Search extends React.Component {
    state = {
        searchResults: [],
        search: ''
    }

    constructor(props) {
        super(props);
        this.onSearchClick= this.onSearchClick.bind(this);
        this.onSearchChange = this.onSearchChange.bind(this);
    }

    componentDidMount() {
        // 从路由参数中获取首页传递过来的搜索结果和关键词
        const routeState = this.props.location.state || {};
        if (routeState.searchResults && routeState.searchKeyword) {
            this.setState({
                searchResults: routeState.searchResults,
                search: routeState.searchKeyword
            })
        }
    }

    onSearchChange(value) {
        this.setState({
            search: value
        })
    }

    // 结果页直接发起新的搜索,不需要返回首页
    onSearchClick() {
        let url = 'http://localhost:3000/search?q=' + encodeURI(this.state.search) + '&json=1';
        axios.get(url)
        .then(response => {
            this.setState({
                searchResults: response.data
            });
        })
        .catch(error => console.log(error));
    }

    render() {
        return (
            <div className="search-page">
                {/* 顶部固定搜索栏,支持继续搜索 */}
                <div className="search-header">
                    <SearchField 
                        className="search" 
                        placeholder='búsqueda' 
                        type="text" 
                        required 
                        value={this.state.search} 
                        onChange={this.onSearchChange}
                        onSearchClick={this.onSearchClick}
                    />
                </div>
                {/* 搜索结果展示区域 */}
                <div className="search-result">
                    {this.state.searchResults.map((item, index) => (
                        <div key={index} className="result-item">
                            {/* 自行填充结果项的展示内容 */}
                            <h3>{item.title}</h3>
                            <p>{item.desc}</p>
                        </div>
                    ))}
                </div>
            </div>
        )
    }
}

路由配置参考

确保你的路由配置已注册对应路径,示例如下:

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import Search from './Search';

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/search" component={Search} />
      </Switch>
    </Router>
  );
}

内容的提问来源于stack exchange,提问作者Selin Mercan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:54:02