Превышена максимальная глубина обновления. в методе рендеринга нет прямого вызова функции

я проверяю другие потоки SO об этой ошибке, они говорят, что у вас есть вызов какой-то функции в методе рендеринга. а вот у меня нет.

он автоматически звонит componentDidMount. Я не знаю, какая часть его называет. пожалуйста помоги

мой компонент

class TeacherDashboard extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            questionPapers: ''
        };
    }
    componentDidMount() {
        this.props.removeError();
        apiCall('get', `${process.env.REACT_APP_BASE_URL}/api/questionpapers`, undefined) //fetch all question set
            .then(data => {
                if (!data.success) {
                    throw Error(data.message);
                }
                else {
                    this.setState({
                        isLoading: false,
                        questionPapers: data.questionPapers
                    })
                }
            })
            .catch(err => {
                this.setState({
                    isLoading: false
                })
                this.props.addError(err.message || 'something went wrong. please try again later.')
            });
    }

    deleteQuestionPaper = (questionPaperId) => {
        apiCall('delete', `${process.env.REACT_APP_BASE_URL}/api/questionpapers/${questionPaperId}`, undefined)
            .then(data => {
                if (!data.success) {
                    throw Error(data.message);
                }
                else {
                    this.setState({
                        questionPapers: this.state.questionPapers.filter((questionPaper) => questionPaper._id !== questionPaperId)
                    })
                }
            })
            .catch(err => {
                this.props.addError(err.message || 'something went wrong. please try again later.')

            });
    }


    render() {
        debugger
        let { isLoading, questionPapers } = this.state;
        let dashboard = questionPapers ? questionPapers.length > 0 ?
            <QuestionPaperInfo  questionPapers = {questionPapers} deleteQuestionPaper = {this.deleteQuestionPaper} /> :
            <div className='bg-danger h2 p-1' >No question paper found. please create one.</div> :
            null;
        return (
            <div className='mt-2'>
                {isLoading ? <p className='h1'>Loading......</p> : dashboard}
                <Link to='/teachers/newquestionpaper' className='btn btn-warning'>Add a new Question paper</Link>
            </div>
        )
    }
}

export default TeacherDashboard;

QuestionPaperInfo компонент

const QuestionPaperInfo = (props) => {
    return (
        <table className = "table table-hover text-center">
          <thead className = "thead-dark">
            <tr>
              <th scope = "col">S.N.</th>
              <th scope = "col">Subject</th>
              <th scope = "col">Class</th>
              <th scope = "col">Total Questions</th>
              <th scope = "col">Total Marks</th>
              <th scope = "col">Action</th>
            </tr>
          </thead>
          <tbody>
          {props.questionPapers.map((questionPaper,i)=>{
             return <tr key = {questionPaper._id||i}>
                <th scope='row'> {i+1}</th>
                <th><Link to = {`/teachers/${questionPaper._id}`}>{questionPaper.subject}</Link></th>
                <th>{questionPaper.standard}</th>
                <th>{questionPaper.totalQuestions}</th>
                <th>{questionPaper.totalMarks}</th>
                <th className='text-danger' onClick = {()=>props.deleteQuestionPaper.bind(null, questionPaper._id )}>Delete</th>
              </tr>
          })}
          </tbody>
        </table>
    )
}

export default QuestionPaperInfo

родительский компонент

import React, { Component } from 'react';
import { withRouter } from "react-router-dom"

const withAuth = (ComponentToBeRendered)=>{
    class Authenticate extends Component {
        componentWillMount() {
            if (!window.localStorage.jwtToken) {
                debugger
                // console.info(this.props)
                this.props.addError('please signin first.');
                this.props.history.push('/auth/signin');
            }
        }
        componentWillUpdate(nextProps) {
            if (!window.localStorage.jwtToken) {
                this.props.addError('please signin first.');
                this.props.history.push('/auth/signin');
            }
        }

        render() {
            return <ComponentToBeRendered removeError = {this.props.removeError} addError = {this.props.addError} />
        }
    }
    return withRouter(Authenticate)
}

export default withAuth;

внутри app.js

render(){
   let WithHocTeacherDashboard = withAuth(TeacherDashboard);
   return
   <Route exact path='/teachers/me' render = {props=> <WithHocTeacherDashboard addError = {this.addError} removeError = {this.removeError} />} /> 
}

он не работает в методе addError в app.js

Я не вижу ничего особенно плохого в вашем коде. Я бы попытался заглянуть в родительский компонент.

Sulthan 17.03.2019 21:37

я обновил код. он работает правильно, если я удалю WithAuth, но мне нужна эта функциональность.

Gouri Shankar 17.03.2019 22:41

Я подозреваю, что запуск действия в componentWillMount вызывает проблему. Вероятно, вам следует обращаться со всей концепцией по-другому.

Sulthan 17.03.2019 23:08
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Массив зависимостей в React
Массив зависимостей в React
Все о массиве Dependency и его связи с useEffect.
1
3
41
1

Ответы 1

Похоже, вы пытаетесь установить состояние в componentDidMount без установки условия, поэтому в основном каждое обновление снова запускает компонент.

попробуйте ввести логику componentDidMount внутри условия, сравнивающего старые реквизиты с новыми.

так

  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    // your logic
  }
} 

ou may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance.

компонентDidMount()

но как остановить этот бесконечный цикл. приведенный выше код перестанет вызывать setState, но не остановит непрерывный рендеринг

Gouri Shankar 17.03.2019 18:52

Другие вопросы по теме