首页 文章

React Native仅重新呈现某些组件

提问于
浏览
0

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

我如何使本地反应只重新渲染受状态影响的一些组件?我在某个地方读到你可以使用关键道具来做,但没有关于如何做的例子 .

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中的文本 .

1 回答

  • 0

    你要找的是 shouldComponentUpdate . 记录here . 另请查看optimizing performance docs .

    tldr:

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

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

相关问题