Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

reactjs - How to prevent reloading the entire component on updating some firestore documents?

I am trying to build a drag and drop to do list...After every drag and drop position of each element is updated in firebase...This is the function doing so

unfinishedTodos.forEach((each, index) => {
 firebaseApp.firestore().collection("todos").doc(each.id).update({
   index: index})
});

But after the update function is run the entire component is reloading..The problem is that since there are lots of items in the list I have to again scroll to find the item i was working with...I want to make sure that the firestore documents get updated but the page should not reload...How can I can prevent this reload? Update: I found out what went wrong...Actually I was using the onSnapshot function of firebase...So on every change it got triggered and reloaded the data...

question from:https://stackoverflow.com/questions/65858735/how-to-prevent-reloading-the-entire-component-on-updating-some-firestore-documen

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

React updates a component whenever any state or props variable changes.

So, to prevent a re-render conditionally, you can use this lifecycle function (returning false means avoiding a re-render):

class component

shouldComponentUpdate(prevState, prevProps) {
    if (this.state.someVariable !== prevState.someVariable || 
        this.props.someVariable !== prevProps.someVariable) {
        return false;
    }

    return true;
}

functional component

React.memo(MyComponent, (props, nextProps)=> {
    if(this.state.someVariable !== prevState.someVariable) {
        // if don't re-render/update
        return true
    }

    //...
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...