我对useEffect感到疯狂。我3个月前开始编码,但我并没有真正的经验。
我有一个父组件,该组件使用useEffect初始化数据库中的一些数据,然后将这些数据作为道具传递给子组件,该子组件使用useEffect初始化数据库中的其他数据。无论我如何尝试,都无法使其正常工作。我认为原因是因为在子组件的初始化完成之前会卸载组件。我一直在阅读文档,但无法弄清楚如何解决此问题。
感谢您能帮助我解决问题。
...
import ModelDesigner from './subComponents/ModelDesigner'
const Model = ({ match }) => {
const [model, setModel] = useState({})
const initialize = async (id) => {
try {
const res = await axios.get(`/model/${id}`)
setModel(res.data)
} catch (err) {
console.log(err.response.data)
}
}
const link = match.params.link
useEffect(() => {
initialize(link)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return (
<ModelDesigner user={model.user} />
)
...
import PropTypes from 'prop-types'
const ModelDesigner = ({ user }) => {
const [profile, setProfile] = useState({})
const loadProfile = async (id) => {
try {
const profile = await axios.get(`/profile/id/${id}`)
setProfile(profile.data)
} catch (err) {
console.log(err.response.data)
}
}
useEffect(() => {
loadProfile(user)
}, [])
return ( ... )
我想我知道这里发生了什么。 Model
是异步初始化的,因此,在首次呈现时,model
变量是一个空对象。
但是,子ModelDesigner
立即呈现,并且其useEffect
回调在从API加载模型之前运行。因此,它可能在调用/profile/id/undefined
而不是使用您想要的配置文件ID。
解决此问题的一种方法是等待呈现子组件,直到完成加载其道具所需的数据为止。对于这个例子,我想这看起来像:
return model.user
? <ModelDesigner user={model.user} />
: <div />
或者,您可以将user
添加为useEffect
的依赖项,如果为空值,则跳过API调用。这样,它将等待尝试初始化,直到获得所需的ID。
const loadProfile = async (id) => {
if (!id) {
return;
}
try {
const profile = await axios.get(`/profile/id/${id}`)
setProfile(profile.data)
} catch (err) {
console.log(err.response.data)
}
}
useEffect(() => {
loadProfile(user)
}, [user])