最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react-router-dom Redirect causes : Maximum update depth exceeded - Stack Overflow

programmeradmin4浏览0评论

I am attempting to redirect from the root url of my app and I get the above error. I have read some of the other answers here on SO that reference this error but they center on state being updated cyclically and I can't see where I'm doing it in the Router:

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" ponent={App} /> {/** */}
            <Route path="/search" ponent={App} />
            <Route path="/" ponent={App} /> 
        </Switch>
            <Route path="/book/:bookId" ponent={BookDetails} />

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

Or in the App.js file which I hope is okay :

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;

I can't demo the code since it involves a REST Api server that's local to my machine. Thanks.

I am attempting to redirect from the root url of my app and I get the above error. I have read some of the other answers here on SO that reference this error but they center on state being updated cyclically and I can't see where I'm doing it in the Router:

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" ponent={App} /> {/** */}
            <Route path="/search" ponent={App} />
            <Route path="/" ponent={App} /> 
        </Switch>
            <Route path="/book/:bookId" ponent={BookDetails} />

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

Or in the App.js file which I hope is okay :

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;

I can't demo the code since it involves a REST Api server that's local to my machine. Thanks.

Share Improve this question asked Apr 22, 2019 at 3:09 kn0tkn0t 3437 silver badges14 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

Well my instructor suggested this : https://reacttraining./react-router/web/api/Switch and I thought I tried this already but I read the docs and tried this -

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

The exact property isn't needed on all the routes. But I thank Kishan for his effort, he definitely was on the right track. Thanks again.

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

try this way, maybe helps you

发布评论

评论列表(0)

  1. 暂无评论