大家好,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模式下只出现一次“注册失败”的文字提示。
以上是我个人针对该报错的解决方法, 仅供参考。
第一次分享也是记录一下,代码写得不好,如果有写的有不正确的地方,希望各位大佬指导一下。感谢先!