# 并行状态节点
¥Parallel State Nodes
这些 XState v4 文档不再维护
XState v5 现已推出!阅读有关 XState v5 的更多信息 (opens new window)
¥XState v5 is out now! Read more about XState v5 (opens new window)
🆕 了解有关 XState 中的并行状态 (opens new window) 和 并行状态的无代码介绍 (opens new window) 的更多信息。
¥🆕 Find more about parallel states in XState (opens new window) as well as a no-code introduction to parallel states (opens new window).
在状态图中,你可以将状态声明为并行状态。这意味着它的所有子状态将同时运行。要了解更多信息,请参阅 状态图简介 中的部分。
¥In statecharts, you can declare a state as a parallel state. This means that all its child states will run at the same time. To learn more, see the section in our introduction to statecharts.
# API
通过设置 type: 'parallel'
在机器和/或任何嵌套复合状态上指定并行状态节点。
¥A parallel state node is specified on the machine and/or any nested compound state by setting type: 'parallel'
.
例如,下面的机器允许 upload
和 download
复合状态同时激活。想象一下,这代表一个可以同时下载和上传文件的应用:
¥For example, the machine below allows the upload
and download
compound states to be simultaneously active. Imagine that this represents an application where you can download and upload files at the same time:
const fileMachine = createMachine({
id: 'file',
type: 'parallel',
states: {
upload: {
initial: 'idle',
states: {
idle: {
on: {
INIT_UPLOAD: { target: 'pending' }
}
},
pending: {
on: {
UPLOAD_COMPLETE: { target: 'success' }
}
},
success: {}
}
},
download: {
initial: 'idle',
states: {
idle: {
on: {
INIT_DOWNLOAD: { target: 'pending' }
}
},
pending: {
on: {
DOWNLOAD_COMPLETE: { target: 'success' }
}
},
success: {}
}
}
}
});
console.log(fileMachine.initialState.value);
// => {
// upload: 'idle',
// download: 'idle'
// }
并行状态节点的状态值表示为一个对象。该对象状态值可用于进一步转换到并行状态节点中的不同状态:
¥A parallel state node's state value is represented as an object. This object state value can be used to further transition to different states in a parallel state node:
console.log(
fileMachine.transition(
{
upload: 'pending',
download: 'idle'
},
{ type: 'UPLOAD_COMPLETE' }
).value
);
// => {
// upload: 'success',
// download: 'idle'
// }
复合状态节点可以包含并行状态节点。嵌套状态节点的配置相同:
¥A compound state node can contain parallel state nodes. The configuration is the same for nested state nodes:
const lightMachine = createMachine({
// not a parallel machine
id: 'light',
initial: 'green',
states: {
green: {
on: {
TIMER: { target: 'yellow' }
}
},
yellow: {
on: {
TIMER: { target: 'red' }
}
},
// nested parallel machine
red: {
type: 'parallel',
states: {
walkSign: {
initial: 'solid',
states: {
solid: {
on: {
COUNTDOWN: { target: 'flashing' }
}
},
flashing: {
on: {
STOP_COUNTDOWN: { target: 'solid' }
}
}
}
},
pedestrian: {
initial: 'walk',
states: {
walk: {
on: {
COUNTDOWN: { target: 'wait' }
}
},
wait: {
on: {
STOP_COUNTDOWN: { target: 'stop' }
}
},
stop: {
type: 'final'
}
}
}
}
}
}
});
console.log(lightMachine.transition('yellow', { type: 'TIMER' }).value);
// {
// red: {
// walkSign: 'solid',
// pedestrian: 'walk'
// }
// }