简体   繁体   English

为什么我的组件在更新后没有重新渲染?

[英]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.我正在尝试更改我的对象数组的 state,它确实更改了 state,但我的组件没有重新渲染。 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仅当您设置 state 时组件才会重新渲染,无论它是基于 class 的组件还是挂钩

1.class based component this.setState() 1.class 基于组件this.setState()

2.hooks setLen() 2.钩子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.对于要重新渲染的组件,必须更新 state。 You need to do the setState for your component to update.您需要执行setState才能更新组件。 Also if you are getting the updated values from props then you should consider using componentDidUpdate lifecycle hook of react.此外,如果您从 props 获取更新的值,那么您应该考虑使用 react 的componentDidUpdate生命周期钩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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