反应重定向到仅加载1个组件

时间:2019-11-14 04:42:24

标签: reactjs react-router

我在我的应用程序中使用搜索后尝试使用重定向到,搜索效果很好,并且没有任何问题。问题是,当它重定向到搜索页面时,加载的组件只是搜索组件和标头组件。

这是我的路由器代码:

<HashRouter>
  <div>
  <Master/>
  <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/home" component={Home} />
    <Route path="/login" component={Login} />
    <Route path="/register" component={Register} />
    <Route exact path="/search/:userId" component={Search} />
    <Route exact path="/produk/:userId" component={Product} />
    </Switch>
    </div>
    </HashRouter>

这是我的master.js(带有搜索头)

    constructor(props){
    super(props);
    this.state = {cari: '', diCari:false};

    this.handleChange1 = this.handleChange1.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange1(e){
    this.setState({
      cari: e.target.value
    })
  }
  handleSubmit(e){
    e.preventDefault();
    const cari = {
      cari: this.state.cari
    }

        this.setState({ diCari: true }); // after signing up, set the state to true. This will trigger a re-render

}

  render(){
    if (this.state.diCari) {
     // redirect to home if signed up
     return <Redirect to = {{ pathname: "/search/" + this.state.cari }} />;
   }

提前谢谢!

1 个答案:

答案 0 :(得分:0)

      <HashRouter>
        <div>
          <Master />
          <Switch>
            <Route exact path="/" render={props => <Home />} />
            <Route path="/home" render={props => <Home />} />
            <Route path="/login" render={props => <Login />} />
            <Route path="/register" render={props => <Register />} />
            <Route exact path="/search/:userId" render={props => <Search />} />
            <Route exact path="/produk/:userId" render={props => <Product />} />
          </Switch>
        </div>
      </HashRouter>

      and this is my master.js(header with the search)


      render(){
        if (this.state.diCari) {
          // redirect to home if signed up
          return <Redirect to={`/search/${this.state.cari}`} />;
        }

进行此更改并检查