【问题标题】:Calling a function automatically when rendering a screen渲染屏幕时自动调用函数
【发布时间】:2017-11-20 21:36:23
【问题描述】:

所以我有一个标题栏,当我使用 stackNavigation 打开个人资料屏幕时会隐藏它

个人资料屏幕:

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 或其他组件的构造函数中)。渲染方法应该是 props 和 state 的纯函数;构造函数副作用是一种反模式,但可以移至componentWillMount

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

【问题讨论】:

  • 也许从构造函数调用props.screenProps.updateHeader(); 是问题所在? Cannot update during an existing state transition (such as within render or another component's constructor).
  • @ewizard 你是对的。从按钮内部调用它是可行的,但问题是我的应用程序通过滑动导航,因此它应该在每次页面呈现时自动调用该函数
  • 哦,我认为错误消息告诉您使用生命周期挂钩 componentWillMount...尝试在您的 ProfileScreen 组件中 - componentWillMount() { props.screenProps.updateHeader(); } 并从构造函数中取出 props.screenProps...跨度>

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


【解决方案1】:

正如精灵所说,从

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多