使用ReactJS实现搜索栏

使用ReactJS实现搜索栏,reactjs,react-router,Reactjs,React Router,我正在构建一个初学者React应用程序,无法理解如何处理我的状态,以便重定向到搜索结果页面: 我有一个主要的应用程序组件,它使用React Router提供两个组件: 1) 着陆(/)--有一个输入,应该带您到/search,只显示标题与您的输入匹配的对象 2) 搜索(/Search)——如果直接访问页面,则显示所有对象,或者根据输入进行过滤 我的问题是:如果我在应用程序组件中处理状态,它将导致状态更新,并在用户键入登录输入元素时重新加载,但我如何让它使用更新的状态转到/搜索?索引路由将不断被点

我正在构建一个初学者React应用程序,无法理解如何处理我的状态,以便重定向到搜索结果页面:

我有一个主要的应用程序组件,它使用React Router提供两个组件:

1) 着陆(
/
)--有一个输入,应该带您到
/search
,只显示标题与您的输入匹配的对象 2) 搜索(
/Search
)——如果直接访问页面,则显示所有对象,或者根据输入进行过滤

我的问题是:如果我在应用程序组件中处理状态,它将导致状态更新,并在用户键入登录输入元素时重新加载,但我如何让它使用更新的状态转到/搜索?索引路由将不断被点击,因为它只是一个重新加载程序,用户仍然在登录页上

我想在没有redux的情况下处理这个问题,因为这将是一个非常小的应用程序

以下是我的父组件的代码:

import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { shape, string } from "prop-types";

import Landing from "./Landing";
import Search from "./Search";
import { shows } from "../data.json";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchTerm: ""
    };
    this.updateSearchTermHandler = this.updateSearchTermHandler.bind(this);
  }

  updateSearchTermHandler(searchTerm) {
    this.setState({ searchTerm });
  }

  render() {
    return (
      <BrowserRouter>
        <div className="app">
          <Switch>
            <Route
              exact
              path="/"
              component={props => (
                <Landing
                  updateSearchTermHandler={this.updateSearchTermHandler}
                  searchTerm={this.state.searchTerm}
                  {...props}
                />
              )}
            />
            <Route
              path="/search"
              component={props => (
                <Search
                  updateSearchTermHandler={this.updateSearchTermHandler}
                  shows={shows}
                  {...props}
                />
              )}
            />
          </Switch>
        </div>
      </BrowserRouter>
    );
  }
}

App.propTypes = {
  match: shape({
    params: string.isRequired
  }).isRequired
};

export default App;
import React,{Component}来自“React”;
从“react router dom”导入{BrowserRouter,Route,Switch};
从“道具类型”导入{shape,string};
从“/Landing”导入着陆;
从“/Search”导入搜索;
从“./data.json”导入{shows};
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
搜索词:“
};
this.updateSearchTermHandler=this.updateSearchTermHandler.bind(this);
}
updateSearchTermHandler(搜索术语){
this.setState({searchTerm});
}
render(){
返回(
(
)}
/>
(
)}
/>
);
}
}
App.propTypes={
匹配:形状({
参数:string.isRequired
}).需要
};
导出默认应用程序;

一个潜在的解决方案是将
与您自己的
历史记录一起使用。然后可以调用
history.replace('/search',{searchTerm:'foo'})

然后在你的登陆组件中,你将拥有
this.props.history.location.state.searchTerm

有关创建历史记录的详细信息,请参见