简体   繁体   English

反应上下文不会导致重新渲染

[英]React context not causing a rerender

Very puzzled by this situation.对这种情况非常困惑。 I have two methods in the context, one causes a rerender in the consumer just fine and the other doesnt.我在上下文中有两种方法,一种会导致消费者重新渲染就好了,而另一种则不会。

This one works fine:这个工作正常:

this.setPage = (tag) => {
            this.setState(state => {

                for (let item of tag) {
                    if (!state.tags.includes(item)) {
                        state.tags.push(item)
                    }
                }

                state.currentTags = tag
                return tag
            })
        }

but this one doesnt:但这个没有:

this.popPage = (tag) => {
            this.setState(state => {                
                if (state.tags.includes(tag)) {
                    if (state.tags.length == 1)
                        return

                    state.tags.pop()
                    state.currentTags = [state.tags[state.tags.length - 1]]

                    return tag
                }
            })
        }

These are basically just pushing and popping items into the array.这些基本上只是将项目推入和弹出到数组中。 The code runs and works fine, but there is no update in the consumer for the second function代码运行正常,但消费者中没有更新第二个功能

<Page.Consumer>
   {page => /*Components go here*/}
</Page.Consumer>

First of all, you should return state (not tag).首先,您应该返回状态(而不是标签)。 I don't know what tag is for exactly but to me it doesn't make much sense that next state is set as tag.我不知道标签究竟是什么,但对我来说,将下一个状态设置为标签没有多大意义。 In the second block, even worse.在第二个街区,情况更糟。 In case condition is not met, it even doesn't return anything as the next state.如果条件不满足,它甚至不返回任何内容作为下一个状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM