简体   繁体   中英

Why is my component not re-rendering after updating it?

I'm trying to change state of my array of objects, it does change state, but my component isn't re-rendering. Why is that?

useEffect(() => {
    if(data && data.rows) {
        data.rows.forEach(async (elem) => {
            const row = await axios.get(url);
            elem.members= row.data.length;
        })
    }
}, [data])

component will re-render only when you set state whether it's class based component or hooks

1.class based component this.setState()

2.hooks setLen()

const [len, setLen] = React.useState(0);
useEffect(() => {
    if(data && data.rows) {
        data.rows.forEach(async (elem) => {
            const row = await axios.get(url);
            setLen(row.data.length);
        })
    }
}, [data])

For a component to re render the state must be updated. You need to do the setState for your component to update. Also if you are getting the updated values from props then you should consider using componentDidUpdate lifecycle hook of react.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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