【问题标题】:React Native rerendering only certain componentsReact Native 仅重新渲染某些组件
【发布时间】:2018-12-16 06:32:01
【问题描述】:

假设我的页面中有 10 个或更多组件,现在每当我使用 setState 更改状态时,react native 会重新渲染所有组件(更改的组件和所有其他实际上不需要更改的组件)。

如何让 react native 只重新渲染一些受状态改变影响的组件?我在某处读到你可以使用 key props 来做到这一点,但没有关于如何做的例子。

export default class MyApp extends React.Component({

    constructor(props) {
        super(props);
        this.state = {
            result: ''
        }
    }

    LoadChild() {
        // Some functions that load a tabnavigator component
    }

    render() {
        return(
            <View style={{ flex: 1}}>
                <ParentComponent>
                    <Text>
                        //Some Text that need to be updated
                        { this.state.result }
                    </Text>

                    <ChildComponent>
                        { this.LoadChild() }
                    </ChildComponent>
                </ParentComponent>
            </View>
        );
    }
});

每当我调用像 setState({ result: 'test' }) 这样改变状态的函数时,我需要 ParentComponent 中的文本重新渲染以显示当前状态,但这也会导致 ChildComponent 重新渲染,导致函数LoadChild() 再次触发,因此 componentDidMount() 也再次触发。我希望状态仅在状态更改时影响 ParentComponent 中的文本。

【问题讨论】:

    标签: javascript reactjs react-native rerender


    【解决方案1】:

    您正在寻找的是shouldComponentUpdate。这记录在here。另请查看optimizing performance docs

    tldr:

    目前,如果 shouldComponentUpdate() 返回 false,则不会调用 UNSAFE_componentWillUpdate()、render() 和 componentDidUpdate()。

    键的用途略有不同,请阅读here

    【讨论】:

    • 嗨,谢谢你的回答,已经调查过了,我尝试了 shouldComponentUpdate,据我了解,它停止了重新渲染的所有内容,我想重新渲染但只有一些组件,我该怎么做分开 shouldComponentUpdate 以便它只重新渲染某些组件?我已经更新并添加了一些代码以便更好地理解。
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 2019-02-26
    • 2021-10-28
    • 2021-01-02
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2021-01-16
    相关资源
    最近更新 更多