渲染屏幕时自动调用函数

时间:2017-11-20 21:36:23

标签: javascript react-native navigation expo stack-navigator

所以当我打开带有stackNavigation的个人资料屏幕

时,我有一个标题栏

ProfileScreen:

export default class ProfileScreen extends React.Component {
    constructor(props) {
        super(props);
        props.screenProps.updateHeader();
    }
// Code goes on
//..........
//................
//...........................
}

从父类调用updateHeader,然后调用函数

主要(家长班):

export default class Main extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            showHeader: true
        };
    }

    updateState = () => {
        this.setState({
            showHeader: !this.state.showHeader
        });
    }

    render() {
        return (
            <View style={styles.container}>
                {renderIf(this.state.showHeader,
                    <Header />
                )}
               <UserStack screenProps={{ updateHeader: this.updateState }} />
             </View>
        );
     }
}

它有效但有点慢。

导出项目时它会更好吗?

我也收到了这个警告:

警告:在现有状态转换期间无法更新(例如在render或其他组件的构造函数中)。渲染方法应该是道具和状态的纯函数;构造函数副作用是一种反模式,但可以移到componentWillMount

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:-1)

ewizard 表示从

调用它
componentWillMount() { this.props.screenProps.updateHeader(); }

而不是构造函数修复了警告。