简体   繁体   English

不变违规错误。 React 最小化错误 #31

[英]Invariant Violation Error. React Minified Error #31

I am rendering a challenge list and it works on my local.我正在渲染一个挑战列表,它适用于我的本地。 But when I deploy it to Netlify, I get some error on console.但是当我将它部署到 Netlify 时,我在控制台上遇到了一些错误。 What is wrong with my code?我的代码有什么问题?

** **

react-dom.production.min.js:4408 Invariant Violation: Minified React error #31; react-dom.production.min.js:4408 Invariant Violation: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Bmessage%7D&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.访问https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Bmessage%7D&args[]=获取完整消息或使用非最小化环境完整的错误和其他有用的警告。 ** **

ChallengeList挑战清单

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'

// Utils and API
import periodConverter from '../../../utils/period-converter'
import fetchChallenges from '../../../API/challenges/fetch-challenges'
import isVisible from '../../../utils/is-challenge-visible'

// Components
import Challenge from '../Challenge'
import Grid from '../../../hoc/Grid'

const ChallengeList = props => {
  // Auth token
  const token = localStorage.getItem('x-auth-token')

  // Store
  const dispatch = useDispatch()  
  const challenges = useSelector(state => state.challenges.all)
  const visibleChallenges = useSelector(state => state.challenges.visible)

  const provideChallenges = () => {
    return fetchChallenges(token, (err, challenges) => {
      if (err) return console.log(err)      
      dispatch({ type: 'SET_CHALLENGES', challenges })
    })
  }

  const filterChallenges = () => {
    let _visibleChallenges = []
    let _hiddenChallenges = []

    if (challenges.length) {
      challenges.map(challenge => {
        if (isVisible(challenge)) _visibleChallenges.push(challenge)
        else _hiddenChallenges.push(challenge)        
      })
      dispatch({ type: 'SET_VISIBLE_CHALLENGES', challenges: _visibleChallenges })
      dispatch({ type: 'SET_HIDDEN_CHALLENGES', challenges: _hiddenChallenges })
    }
  } 

  // Component did mount
  useEffect(() => {
    if ( token ) {
      provideChallenges()    
    }    
  }, [])

  // Challenges updated. Filter them as visible and hidden
  useEffect(() => {
    filterChallenges()    
  }, [challenges])  

  return (
    <Grid>
      {
        visibleChallenges.length
        ? visibleChallenges.map(challenge => {
            const period = periodConverter(challenge.period)

            return <Challenge
                    key={challenge._id}
                    _id={challenge._id}
                    name={challenge.name}
                    image={challenge.image}
                    info={challenge.imageInfo}
                    period={period}
                    pointAmount={challenge.pointAmount}
                    day={challenge.day}
                  />      
        })
        : <p>There is no any todo!</p>
      }
    </Grid>
  )
}

export default React.memo(ChallengeList)

Challenge挑战

import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import moment from 'moment'

// Utils and API
import timer from '../../../utils/timer'
import updateChallenge from '../../../API/challenges/update-challenge'
import updateState from '../../../API/states/update-state'
import { isChallengeDay, isChallengePeriod } from '../../../utils/is-challenge-visible'

// Style
import './style.scss'

// Images
import breakfastImage from '../../../assets/images/challenges/breakfast.gif'
import brushingImage from '../../../assets/images/challenges/brushing.gif'
import candydayImage from '../../../assets/images/challenges/candyday.gif'
import lunchImage from '../../../assets/images/challenges/lunch.gif'
import milkImage from '../../../assets/images/challenges/milk.gif'
import sleepingImage from '../../../assets/images/challenges/sleeping.png'
import wakeupImage from '../../../assets/images/challenges/wakeup.gif'

const images = {
  breakfast: breakfastImage,
  brushing: brushingImage,
  candyday: candydayImage,
  lunch: lunchImage,
  milk: milkImage,
  sleeping: sleepingImage,
  wakeup: wakeupImage
}

const Challenge = props => {
  // Auth Token
  const token = localStorage.getItem('x-auth-token')

  // Dispatch function to set challenges
  const dispatch = useDispatch()

  // Declare a variable to keep visibility of component
  let visible = true

  /* State */
  const [day, setDay] = useState(moment().format('dddd'))
  const [time, setTime] = useState(moment().format('HH:mm:ss'))
  const [leftTime, setLeftTime] = useState('00:00:00')

  /* Thumbnail Image */  
  const image = images[props.image.toLowerCase().split('.')[0]]

  /* Sets current day, current time and left time to catch the challenge */
  const timeHandler = () => {
    // Set current time and day
    const _day = moment().format('dddd')
    const _time = moment().format('HH:mm:ss')

    setDay(_day)
    setTime(_time)

    // If period exist, calculate left time
    if (props.period) {
      const timerOutput = timer(props.period[0], props.period[1])
      setLeftTime(timerOutput)
    }
  }

  const challengeCompleted = () => {
    const today = moment().format('YYYY-MM-DD')
    const body = { completedDate: today }

    updateChallenge(props._id, body, token, (err, challenge) => {
      if (err) return console.log(err)

      dispatch({
        type: 'ADD_HIDDEN_CHALLENGE', id: challenge.data._id
      })

      const payload = { name: 'total', state: challenge.data.pointAmount, action: 'increase' }

      updateState(payload, token, (err, doc) => {
        if (err) return console.log(err)
        dispatch({ type: 'SET_TOTAL_POINT', point: doc.state })
      })
    })
  }

  // componentDidMount
  useEffect(() => {
    const intervalTimer = setInterval(timeHandler, 1000)

    // before componentDidUnmount, reset the timer
    return () => {
      clearInterval(intervalTimer)
    }
  }, [])

  // componentDidUpdate : day has changed
  // Update the challenges whether challenge is on day or not
  useEffect(() => {
    if (visible && props.day && !isChallengeDay(props.day, day)) {
      dispatch({ type: 'ADD_HIDDEN_CHALLENGE', id: props._id })
    }
    else if (!visible && props.day && isChallengeDay(props.day, day)) {
      dispatch({ type: 'ADD_VISIBLE_CHALLENGE', id: props._id })
    }
  }, [day])

  // componentDidUpdate : time has changed
  // Update the challenges whether challenge is on period or not
  useEffect(() => {
    if (visible && props.period && !isChallengePeriod(props.period, time)) {
      dispatch({ type: 'ADD_HIDDEN_CHALLENGE', id: props._id })
    }
    else if (!visible && props.period && isChallengePeriod(props.period, time)) {
      dispatch({ type: 'ADD_VISIBLE_CHALLENGE', id: props._id })
    }
  }, [time])

  // componentDidUpdate (time or points is changed)
  useEffect(() => {

  }, [leftTime])  

  return visible === true 
    ? <div className='challenge'>
        {/* Image */}
        <div className='challenge__image'>
          <img src={image} alt={props.info} />
        </div>

        {/* Footer */}
        <div className='challenge__footer'>
          {/* Timer */}
          <div> { props.period.length > 0 && leftTime } </div>

          {/* Point Amount */}
          <div className='challenge__pointAmount'>          
            {props.pointAmount} <i className='fa fa-heart' />
          </div>

          {/* Button */}
          <div className='challenge__button' onClick={challengeCompleted}>
            <i className='fa fa-check' />
          </div>
        </div>
      </div>    
    : null
}

export default React.memo(Challenge)

Grid网格

import React from 'react'
import './style.scss'

const Grid = props => {
  return <div className='grid bg-primary'> {props.children} </div>
}

export default Grid

Whenever you see such an error you can visit the page it suggests to see the full error.每当您看到此类错误时,您都可以访问它建议的页面以查看完整错误。 So, when opening https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Bmessage%7D&args[]= , you can see that:所以,当打开https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Bmessage%7D&args[]=时,你可以看到

Objects are not valid as a React child (found: object with keys {message}). If you meant to render a collection of children, use an array instead.

Somewhere you render a component that is not a string, number, boolean, or an array of them.在某处渲染一个不是字符串、数字、boolean 或它们的数组的组件。 Inspect your props and find the one that is an object with a 'message' key inside then you'll know what's you are trying to render incorectly.检查你的道具,找到一个 object,里面有一个“消息”键,然后你就会知道你试图错误地渲染什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM