I've spent a long time chasing down a solution to this problem and I'll pass on what I know.
There is no single cause of cramping. Everyone is different, and many folks have multiple issues that they need to solve. I won't go into the why it happens (though again, Pickles could likely give quite a lecture on the physiology if that is of interest) but here are some of the things that seem to help, in order of impact:
1. Sleep. By far the most impactful thing for most people as far as my experience. If you are training hard and not sleeping you are setting yourself up for a series of issues, cramping being one. (I think this book is great, by the way, and this is partially covered here:
https://www.amazon.com/Good-Go-Athle.../dp/039325433X)
2. Calcium/Magnesium supplements. They really do work. Lots of them are marketing under names like "sport legs" but I've found you can just use bulk stuff from Costco.
3. Tylenol. Little known, but Tylenol can enhance endurance and seems to fight cramps. Not sure how - I read a number of studies on this which seem to be totally gone from my mind now. Would not recommend this be a routine supplement for obvious reasons.
4. Salts. Heavy doses. I like the Gatorade gatorlytes, but only half the pouches at a time.
https://www.amazon.com/Gatorade-Endu.../dp/B0050Q4DJS. In theory this is far better for long efforts, but it seems to help me for stuff between 1 and 2 hours.
5. Fluids with carbs. I am always surprised at how little impact this seems to have, but in extreme circumstances (ie, you just aren't drinking or eating at all) it can get you out of the hole. Most non-beginner people naturally eat and drink enough to keep from cramping from due to this however (in my experience). (now, drinking/eating enough to maintain performance is a different issue entirely)
6. Pickle juice, mustard, etc. Yeah, anecdotally helps. I understand the theory behind the mechanism, just not sure it's not placebo.
7. Ok, this one is weird: phosphoric acid. As in, don't drink it (it's a major ingredient in most soft drinks.) My wife is a human health scientist and she worked with this guy who swore up and down that it pulled calcium out of your system and could cause muscle cramps under high loads. I did not believe it, but tried it. It worked for me. I don't think it was placebo, and there is science behind it.
8. Potassium. Again, makes sense in theory, but rarely the issue in my experience.
Hope this helps.
Bookmarks