【问题标题】:Which life cycle method is preferred when using redux and react hooks?使用 redux 和 react hooks 时首选哪种生命周期方法?
【发布时间】:2020-09-29 15:33:31
【问题描述】:

在编辑页面中,通过redux useSelector 方法数据可用于组件但它没有设置初始值。如何设置?

  1. 如何从 store 中设置初始 formData?
  2. 为什么在钩子组件中会发生 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

【问题讨论】:

标签: reactjs redux react-hooks react-lifecycle-hooks


【解决方案1】:
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])

使用Effect Hook作为componentDidMount、componentDidUpdate和componentWillUnmount的组合。

当存储组件可用的值时,props.user 具有属性和值,然后 componentDidUpdate 方法起作用。

useEffect 方法也防止了不必要的渲染。

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 2018-12-21
  • 2019-04-14
  • 2019-10-08
  • 2017-02-11
  • 1970-01-01
相关资源
最近更新 更多