如何从 Reactjs 中的 useEffect 钩子访问道具 [英] How to access props from useEffect hook in Reactjs

查看:23
本文介绍了如何从 Reactjs 中的 useEffect 钩子访问道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从新闻 API 获取数据并在完成后将其存储在我的状态中,然后还将状态值作为道具传递给子组件.

API 返回的数据是一个对象数组.我只想将该数组(现在处于我的状态)的一个元素(对象)传递给我的子组件.因此,我通过使用数组常规遍历方法 ([]) 传递一个元素来做到这一点,但不幸的是,当我尝试在子组件中使用 useEffect 钩子来控制台记录道具(有效)时,我无法从钩子和组件主体访问我的元素(对象)的属性,因为它一直告诉我它未定义,并且我必须在 useEffect 清理函数中取消所有订阅和异步任务.因此,我尝试使用 splice 方法将该元素作为数组传递,以便使用 map 方法(有效)从子组件遍历,但是,我仍然无法从 useEffect 钩子访问属性.

父组件(Home.js)

<代码> ...const [数据,setData]= useState([])useEffect(()=>{const fetch= async()=>{const response= await axios(url)const 结果= response.datasetData(results.articles.slice(0,5))}拿来()},[网址])返回(<><Categories onClick={fetchCategory}/><section className={classes.latest}><垂直postArray={data.slice(0,1)} postObject={data[0]}/></节></>)}导出默认首页

子组件(Vertical.js)

const Vertical=(props)=>{useEffect(() => {//console.log('postArray',props.postArray.title)console.log('postObject',props.postObject.title)}, )返回(<>{/* 
<figure className={classes.article_figure}><img src='' alt="文章替代品"/></图><div className={classes.article_details}><h2>{props.postObject.title}</h2><p>{props.postObject.description}</p>

</文章>*/}{props.postArray.map(post=>(<文章键={post.content} className={classes.article}><figure className={classes.article_figure}><img src='' alt="文章替代品"/></图><div className={classes.article_details}><h2>{post.title}</h2><p>{post.description}</p>

</文章>))}</>)}导出默认垂直

这样做的原因是我需要访问传递对象内的 URL,以便让另一个 URL 获取该帖子的缩略图.

解决方案

你需要给 useEffect 提供依赖,以便它观察和控制

useEffect(() => {//console.log('postArray',props.postArray.title)console.log('postObject',props.postObject.title)},[props.postObject.title])//这将确保这个道具被监视变化

编辑:对于所有未定义的错误,您可以在依赖项中进行以下更改

useEffect(() => {//console.log('postArray',props.postArray.title)console.log('postObject',props?.postObject?.title)//可选链会处理未定义的检查},[props?.postObject?.title])//可选链会处理未定义的检查

I am fetching data from a news API and storing it in my state upon completion, then also passing the value of the state as props to a child component.

The data returned by the API is an array of objects. I only want to pass one element (object) of that array(which is now in my state) to my child component. So, I did just that by using the arrays conventional traversal method ([]) to pass one element, but unfortunately, when I tried using the useEffect hook in my child component to console log the props (which worked ), I was unable to access the properties of my element (object) from neither the hook nor from the body of the component as it kept on telling me that its undefined and that I have to cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. So I tried passing that one element as an array using the splice method in order to be traversed from the child component using the map method (which worked), however, I was still unable to access the properties from the useEffect hook.

Parent Component (Home.js)

 ...
const [data, setData]= useState([])
 useEffect(()=>{

        const fetch= async()=>{
            const response= await axios(url)
            const results= response.data
            setData(results.articles.slice(0,5))
        }
        fetch()

    },[url])

return(
    <>
    <Categories onClick={fetchCategory}/>
    <section className={classes.latest}>
    <Vertical postArray={data.slice(0,1)} postObject={data[0]}/>
    </section>
    </>
)
}

export default Home

Child component (Vertical.js)

const Vertical=(props)=>{

useEffect(() => {
    // console.log('postArray',props.postArray.title)
    console.log('postObject',props.postObject.title)

}, )

return(
    <>
    {/* <article key={props.postObject.content} className={classes.article}>
        <figure className={classes.article_figure}>
            <img src='' alt="article alternative"/>
        </figure>
        <div className={classes.article_details}>
            <h2>{props.postObject.title}</h2>
            <p>{props.postObject.description}</p>

        </div>
    </article> */}
    {props.postArray.map(post=>(
        <article key={post.content} className={classes.article}>
        <figure className={classes.article_figure}>
            <img src='' alt="article alternative"/>
        </figure>
        <div className={classes.article_details}>
            <h2>{post.title}</h2>
            <p>{post.description}</p>

        </div>
    </article>
    ))}
    </>
)
}

export default Vertical

The reason for this is that I need to access an URL which is inside the passed object in order to make another to fetch the thumbnail for that post.

解决方案

you need to give dependencies to the useEffect, for it to watch and console

useEffect(() => {
    // console.log('postArray',props.postArray.title)
    console.log('postObject',props.postObject.title)

},[props.postObject.title]) //this will ensure that this prop is watched for changes

Edit: for all those with undefined errors you can do the following change in the dependency

useEffect(() => {
        // console.log('postArray',props.postArray.title)
        console.log('postObject',props?.postObject?.title) // optional-chaining would take care of the undefined check 
    
    },[props?.postObject?.title]) // optional-chaining would take care of the undefined check 

这篇关于如何从 Reactjs 中的 useEffect 钩子访问道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆