React useEffect是一种有限循环的变化方法



我已经创建了一个组件:

const [address, setAddress] = useState({street: 'via roma', number: 2})
const onChangeAddress = (newAddress) => {
setAddress(newAddress)
}
<Address initialAddress={address} onChange={onChangeAddress}/>

地址组件的详细信息:

const Address = (props) => {
const {address, onChange} = props
const [addressLocation, setAddressLocation] = useState()
useEffect(() => {
setAddressLocation(address)
}, [address])
const onChangeStreet = (event: React.ChangeEvent<any>): void => {
setAddressLocation(previousState => ({ ...previousState, street: event.target.value }))
}
const onChangeNumber = (event: React.ChangeEvent<any>): void => {
setAddressLocation(previousState => ({ ...previousState, number: event.target.value }))
}
useEffect(() => {
onChange(addressLocation)
}, [addressLocation])
return <div>
<input value={addressLocation.street} onChange={onChangeStreet} />
<input value={addressLocation.number} onChange={onChangeNumber} />
</div>
}

为什么接收此错误"超过了最大更新深度"。当组件在useEffect内部调用setState时,可能会发生这种情况,但useEffect没有依赖数组,或者其中一个依赖项在每次渲染时都会发生变化?

创建更改值和初始化输入的方法的过程是什么?

只要addressLocation发生变化,就会更新addressLocation,导致无限循环

useEffect(() => {
onChange(addressLocation) //u call the onchange props
}, [addressLocation])

useEffect(() => {
setAddressLocation(address) // you are updating the addressLocation again
}, [address]) //ur onchange props change the props.address

你可能应该只打一次电话。

useEffect(() => {
setAddressLocation(address)
}, [])

或者根本不使用props.onChange

最新更新