简体   繁体   English

使用 redux 和 react 钩子时首选哪种生命周期方法?

[英]Which life cycle method is preferred when using redux and react hooks?

In the edit page, by redux useSelector method data available to the component but it is not setting initial values.在编辑页面中,通过 redux useSelector 方法数据可用于组件但它没有设置初始值。 How to set it?如何设置?

  1. How to set the initial formData from the store?如何从商店设置初始 formData?
  2. In hook component rendering happens 4 times why?在钩子组件渲染中为什么会发生 4 次?

 import React,{useState} from 'react' import { useSelector } from 'react-redux' import {updateUserInfo} from '../actions/User' const EditUser = (props) => { const user = useSelector(state => state.user) const [formData, setFormData] = useState({email: user.email ,fullName: user.fullName}) console.log(user) const handleSubmit = e =>{ e.preventDefault(); const id = props.match.params.id const data = new FormData() data.append('email', formData.email) data.append('fullName', formData.fullName) data.append('image', formData.image) props.dispatch(updateUserInfo(id,data,props.history)) // console.log(formData) } const handleChange = e =>{ setFormData({...formData, [e.target.name]: e.target.value }) } const fileHandle = (e) =>{ // console.log(e.target.files) setFormData({...formData,image: e.target.files[0]}) } return ( <React.Fragment> <h2>Edit Account</h2> {Object.keys(user).length > 0 && <> <form onSubmit={handleSubmit}> <label htmlFor="fullName">Full Name</label> <input type="text" name="fullName" value={formData.fullName} onChange={handleChange}/> <br /> <label htmlFor="email">Email</label> <input type="email" name="email" value={formData.email} onChange={handleChange}/> <br /> <label htmlFor="image">Upload Image</label> <input type="file" name="image" onChange={fileHandle}/> <br /> <button >Update</button> </form> </> } </React.Fragment> ) } export default EditUser

useEffect(() => {
        setFormData({email:props.user.email || "", fullName: props.user.fullName || ""}) // update the state if data else it is empty string, if not mentioned empty string you will warning uncontrolled component to controlled component vice-versa 
    },[props.user])

useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. useEffect Hook 作为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。

When store value available to the component, props.user has properties and values then componentDidUpdate method works.当存储可供组件使用的值时,props.user 具有属性和值,然后 componentDidUpdate 方法起作用。

unnecessary rendering also prevented with useEffect method. useEffect 方法还可以防止不必要的渲染。

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

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