【问题标题】:How to setState inside render?如何在渲染中设置状态?
【发布时间】:2018-11-29 23:42:03
【问题描述】:

首先,我尝试检查用户的 ID 是否与 DB 中的 ID 匹配。如果是这样,那么为hasAppliedtoggle 设置一个新状态,但我收到以下警告Cannot update during an existing state transition (such as within 'render' or another component)...

我什至尝试调用一个在渲染之外的函数并且说同样的事情。但是,如果我通过按钮组件的onPress={} 方法在渲染之外调用该函数,那么一切都很好。但在这种情况下,我需要在用户访问页面时首先检查这一点,如果 hasApplied 返回 false 然后使用按钮

render() {
        let { hasApplied } = this.state;
        let { toggle } = this.state;
        let matchUserId = [];
        const textValue = toggle ? 'APPLIED' : 'APPLY NOW';
        const buttonBg = toggle ? '#848d95' : '#34ed1c';
        const buttonState = toggle ? 'false' : 'true';
        const { navigation } = this.props;
        const { goBack } = this.props.navigation;
        const { jobBusiness, locationBusiness } = this.props.navigation.state.params;
        let { user, location, job, data, business } = this.props.navigation.state.params;

        // Check the available applied ids and concatenate objects in Array
        // Check if user_id match any of appliedUserId 
        if (!hasApplied) {
            job.applied.map(o => {
                matchUserId.push(o.user_id);
            });
            const resultUserId = [].concat.apply([], matchUserId);
            hasApplied = resultUserId.includes(this.props.user_id)
            // this.onButtonPress()
            this.setState({hasApplied: true, toggle: true})
        }

谁能解决这个问题?

谢谢

【问题讨论】:

标签: javascript reactjs react-native


【解决方案1】:

使用 React,你不应该也不需要在 render() 中设置状态。

我建议将您的状态检查放在 componentDidMount() 中。它的作用是保证在渲染组件时执行 componentDidMount() 函数中的任何代码,允许您执行检查、设置器等。

基本上,这样做:

componentDidMount() {
    // check if the user ID matches what's in the database
    // if the above is true, setState as needed
}

请注意,您可以使用三元表达式在 React 渲染中显示或不显示内容。让我举个例子:

    { (this.state.whateverStateYouWantToCheck)
      ? <div className="class-of-your-choice">Content you wish to display.</div>
      : null }

在上面,如果this.state.whateverStateYouWantToCheck为真,'?'后面的代码将被渲染。如果为 false,则不会呈现任何内容(null)。

最后一件事,因为在这种情况下我不知道您的组件/容器结构是什么,所以我不确定您引用的用户 ID 是存储在该组件中还是父容器中。如果它在父容器的状态下可用,您肯定希望将它作为道具传递下去。如果您对此实施有任何疑问,请告诉我!

使用我描述的方法,您可以在这里找到一个很好的解决方案。

【讨论】:

    猜你喜欢
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多