2017-07-24 45 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更詳細的信息創造歷史