react-router-dom重定向原因:超过最大更新深度

时间:2019-04-22 03:09:38

标签: javascript reactjs react-router

我试图从我的应用程序的根URL重定向,但出现上述错误。我已经在SO上阅读了其他一些引用此错误的答案,但是它们集中在状态被周期性地更新的过程中,而我在路由器中看不到我正在做的事情:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route, Switch, Redirect} from 'react-router-dom'
import BookDetails from './BookDetails'
import NavBar from './NavBar'
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
    <>
        <Router>
        <NavBar/>
        <Switch>
            <Redirect from="/" to="/search" component={App} /> {/** */}
            <Route path="/search" component={App} />
            <Route path="/" component={App} /> 
        </Switch>
            <Route path="/book/:bookId" component={BookDetails} />

        </Router>
    </>
    , document.getElementById('root'));

或者在我希望 的App.js文件中:

import React, {useState, useEffect} from 'react'
import {Link} from 'react-router-dom'
// import debounce from 'lodash'
import noimage from './noimage.png'
import axios from 'axios'
import './App.css';

const App = (props) =>{

  const [books,setBooks] = useState([])
  const [isLoading,setIsLoading] = useState(false)
  const [hasError,setHasError] = useState(false)
  const [searchTerm,setSearchTerm] = useState('')
  console.log("props",(props.history.location.pathname))
  const input = str => {
    console.log(str)
    setSearchTerm(str)
    getData(str)
  }

  const getData = async () => {
    if(searchTerm && searchTerm.length >= 2){
      if(isLoading === false)setIsLoading(true)
      let s = `http://localhost:7000/books/search/${searchTerm}`
      await axios.get(s)
      .then(resp => {
        console.log(resp.data.books)
        if(books === [])setBooks([...resp.data.books])
        //props.history.push(s)
      })
      .catch(error => {
        console.log(error)
        setHasError(true)
        setIsLoading(false)
      })
    }
    if(isLoading === true) setIsLoading(false)
  }

  const img = {
    height : "175px",
    width : "175px"
  }

  // useEffect(() =>{
  //     setTimeout(() => getData(),2250)
  // },[])



  return isLoading ? (
    <div className="App">
      <div className="spinner"></div>
      <div className="App loading">
        <p><i>loading...</i></p>
      </div>
    </div>
  )
  : hasError ? (
    <div className="App loading-error">
      &#x26A0; There is a network issue: Please try again later
    </div>
  )
  :
  (
    <div className="App">
      <div className="search">
        <div className="container">
          <div className="content">
              <input
                type="search"
                placeholder="Search..."
                aria-label="Search"
                className="search-form"
                value={searchTerm}
                onChange={e => input(e.target.value)}
              />
          </div>
        </div>
      </div>

    {
      (books && books.length >= 1) && 
        books.map((b,i) => {
        console.log(typeof b.imageLinks)
        return (
          <div key={`${b.title}-${i}`} className="search-book">
            <Link to={`/book/${b.id}`}>
              {
                (b.imageLinks === undefined || b === undefined || b.imageLinks.thumbnail ===  undefined) ?
                  <img src={noimage} alt ="Missing" style={img}></img>
              :
                  <img src={b.imageLinks.thumbnail} alt={b.title}></img>
              }
            </Link>
            <p>{b.title}</p>
            <hr/>
          </div>
        )}
      )
    }         
    </div>
  )  
}

export default App;

我无法演示代码,因为它涉及我的计算机本地的REST Api服务器。谢谢。

2 个答案:

答案 0 :(得分:1)

 <>
    <Router>
    <NavBar/>
    <Switch>
        <Redirect  from="/" to="/search" component={App} /> {/** */}
        <Route exact path="/search" component={App} />
        <Route exact path="/book/:bookId" component={BookDetails} />
    </Switch>
    </Router>
</>

尝试这种方式,也许可以帮助您

答案 1 :(得分:0)

我的老师建议这样做:https://reacttraining.com/react-router/web/api/Switch 并且我以为 我已经尝试过了 ,但是我阅读了文档并尝试了-

    (
        <Router>
            <NavBar/>
            <Switch>
                <Redirect exact from="/" to="/search" component={App} />
                <Route path="/search" component={App} />
                <Route path="/book/:bookId" component={BookDetails} />
            </Switch>
        </Router>
    )

并非所有路由都需要exact属性。但我要感谢Kishan所做的努力,他绝对是在正确的道路上。再次感谢。