2017-07-24 20 views
0

我建立一个初学者实现搜索栏作出反应的应用程序,我不能够理解如何处理我的状态,这样我可以重定向到一个搜索结果页面:使用ReactJS

我有一个使用反应的主要应用程序组件路由器提供两个组件:

1)着陆(/) - 有一个输入,并应采取你/search,仅显示其标题这些对象符合您输入 2)搜索(/search) - 无论是显示所有对象如果直接访问该页面或根据您的输入进行过滤

我的问题是:如果我处理App组件中的状态,它将导致状态更新并在用户输入Landing input元素时重新渲染,但是如何才能使用更新州?索引路线将继续受到打击,因为它只是重新呈现,用户仍在着陆页上。

我想处理这个没有REDX,因为这将是一个非常小的应用程序。

这里是我的父组件的代码:

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; 

回答

0

一个潜在的解决方案是改为使用<Router>用自己的history。然后,您可以拨打history.replace('/search', { searchTerm: 'foo' })

,然后在着陆组件,您将有this.props.history.location.state.searchTerm

https://reacttraining.com/react-router/web/api/Router更详细的信息创造历史