Dogs jerk and twitch in their sleep because they are dreaming. From the movement of their legs it's assumed that they are dreaming that they are running.
Dogs dream just as people do. When we dream, sometimes we can have involuntary movements related to what we are dreaming. Dogs do the same thing. Sometimes they can appear to be trying to run or play, which would explain the jerking movements.
Just like humans, dogs dream. The theory is that dogs relive their day, including running, sniffing, and playing. The jerking in their sleep is like a pantomime of their day.