“Render methods should be a pure function of props and state.“组件非StrictMode模式下更新两次,StrictMode模式下是四次

大家好,React框架前端新手,遇到了如下的报错信息:

Warning: Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.

 控制台上述报错,且组件触发了2次更新(非严格模式下就触发了2次,StrictMode严格模式下触发了4次)。

问题原因,参考(转载自),感谢这位大佬博主的分享:

(28条消息) “Render methods should be a pure function of props and state.“这报错啥原因_Meta.Qing的博客-CSDN博客

展示问题如下:

 代码如下:

import { Button, Form, Input, message } from 'antd'
import Layout from "./layout"
import { useDispatch, useSelector } from 'react-redux'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { useEffect } from 'react'
import * as registerActions from '../../actions/register.actions'

function Register () {
  const dispatch = useDispatch()
  const handleRegister = values => {
    dispatch({type: 'register', payload: values})
  }
  
  const state = useSelector(state => state.register)

  // 错误写法
  // const showError = () => {
  //   if (state.loaded && !state.success) {
  //     message.info('注册失败')
  //   }
  // }

  // 正确写法
  const showError = useEffect(() => {
    if (state.loaded && !state.success) {
      return message.info('注册失败')
    }
  })

  return (
    <Layout title="注册" subTitle="">
      {/* 错误写法 */}
      {/* {showError()} */}
      
      {/* 正确写法 */}
      {showError}
      <Form onFinish={handleRegister}>
        <Form.Item
          label="昵称"
          name='name'
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="邮箱"
          name="email"
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="密码"
          name="passord"
        >
          <Input.Password></Input.Password>
        </Form.Item>
        <Form.Item>
          <Button htmlType='submit' type='primary'>注册</Button>
        </Form.Item>
      </Form>
    </Layout>
  )
}

const mapStateToProps = state => {
  return {
    register: state.register
  }
}

const mapDispatchToProps = dispatch => {
  return bindActionCreators(registerActions, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Register)

代码问题片段:使用上述17行~22行,及34行的写法时,控制台将出现文章开头的报错信息,并在非StrictMode模式下出现两次“注册失败”的文字提示。

解决方法:改成使用24行~29行,及37行的写法,控制台就不报错了,而且在非StrictMode模式下只出现一次“注册失败”的文字提示。

 

以上是我个人针对该报错的解决方法, 仅供参考。

第一次分享也是记录一下,代码写得不好,如果有写的有不正确的地方,希望各位大佬指导一下。感谢先!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值