Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - How do I maintain the new order of my items after I use drag and drop and refresh the page?

I'm using this drag and drop library to be able to reorder a list of articles on my page: https://github.com/atlassian/react-beautiful-dnd

However, even though I'm able to drag them up and down and re-order them, when I refresh the page they go back to their initial state.

The articles are pulled from Cloud Firestore.

How can I make them maintain the new order each time I move things around?

class Articles extends Component {
  constructor(props) {
    super(props);
    this.ref = firebase.firestore().collection("articles");
    this.unsubscribe = null;
    this.onDragEnd = this.onDragEnd.bind(this);
    this.state = {
      articles: [],
    };
  }

  onCollectionUpdate = (querySnapshot) => {
    const articles = [];
    querySnapshot.forEach((doc) => {
      const { title } = doc.data();
      articles.push({
        key: doc.id,
        title,
      });
    });
    this.setState({
      articles,
    });
    this.onDragEnd = this.onDragEnd.bind(this);
  };

  componentDidMount() {
    this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate);
  };

  onDragEnd(result) {
    if (!result.destination) return;
        
    const items = this.state.articles;
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    this.setState(items)
  } 

Then in my return(), I've got something like:

<DragDropContext onDragEnd={this.onDragEnd}> ... />
question from:https://stackoverflow.com/questions/65853338/how-do-i-maintain-the-new-order-of-my-items-after-i-use-drag-and-drop-and-refres

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

1 Answer

0 votes
by (71.8m points)

You are fetching data from a remote source. So u need to update that remote source after reordering. You have to do this inside onDragEnd function. Currently you are only updating your local state with this.setState(items). That's why you lose your reorder on page refresh.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...