When people sleep, nerve cells are widely inhibited, but this inhibition process is incomplete. So some nerves in the cerebral cortex are still excited, which leads to dreams.
It can be seen that dreams occur when a few cells in the cerebral cortex are active. If the activities of a few cells lose the control and regulation of the whole cerebral cortex when they are awake, some fragments of memory will be revived without restraint, then people will have strange dreams.