I have found this sooooo difficult. I still do, actually, but I've learned some very useful "tricks".
I used to think that "play it until you know it" was the best way. Wrong. Wrrrrong, it's the worst. You get a muscle memory and unfortunately it is totally unreliable. In a nervous situation, for instance a recital when things are not quite as they use to be, you might end up with a total blackout, just as the one you described.
I also one day discovered that I tried memorizing note by note ...
The best thing is to analyze the piece musically and try to find the structures. If you learn that this bar consists of a G Major chord, followed by a D Major chord and then you play 1½ G Major scale down and end on D (ok, you got that), then you will not lose it that easily, even if the chords are a bit reversed. You can even try to simplify the notes in order to find a structure or a pattern. Can you, for instance, easily answer questions like "which note do you start the coda section with? What is the value of that note?"
Also divide the piece in small chunks. If you get lost in chunk 23, you will still be able to be back on track in chunk 24, and so on.
I find it terribly difficult to memorize HT, and whenever I do that, I'm back in muscle memory mode. So, I memorize HS nowadays, and I find that much, much easier. I also find it easier to learn as much memorization as possible BEFORE I actually try to learn how to play it. You must be able to play it mentally before you go to the piano, at least HS. Of course this does not mean you must learn to play HT without even having the score in front of you.
I am known to have an excellent memory in other contexts, but this piano thing ... I could not believe how stupid I was, as I just COULD NOT learn anything by heart. But finally I had to understand that I used wrong algorithms. Analyzing the structure is a rather tedious job, but it sure pays off.