【问题标题】:react redirect to only load 1 component反应重定向只加载1个组件
【发布时间】:2019-11-14 04:42:24
【问题描述】:

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

这是我的路由器代码:

<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 }} />;
   }

提前致谢!!

【问题讨论】:

  • this.state.cari 这是一个错字吗?应该是this.state.diCari ?
  • 不,this.state.cari 是搜索输入的值。就像我说的那样,搜索没有错
  • 能不能写代码sn-p,让大家有更好的思路?
  • @NaufalSyauqi 你能写出搜索和标题组件的完整代码吗?
  • 能否添加调用handleSubmithandleChange1的代码?

标签: reactjs react-router


【解决方案1】:
      <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}`} />;
        }

进行此更改并检查

【讨论】:

  • 在重定向和检查中进行更改
猜你喜欢
  • 2022-06-29
  • 1970-01-01
  • 2020-11-09
  • 2022-12-10
  • 2021-07-28
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 2021-05-28
相关资源
最近更新 更多