乐闻世界logo
搜索文章和话题

What control flow components are in SolidJS? How to use Show, For, Switch, etc.?

2月21日 15:23

SolidJS provides various control flow components for conditional rendering and list rendering:

Conditional Rendering:

javascript
// Show - Conditional rendering (similar to React's conditional rendering) <Show when={isLoggedIn()} fallback={<Login />}> <Dashboard /> </Show> // Switch - Multiple condition branches <Switch fallback={<NotFound />}> <Match when={status() === 'loading'}> <Loading /> </Match> <Match when={status() === 'success'}> <Success /> </Match> <Match when={status() === 'error'}> <Error /> </Match> </Switch>

List Rendering:

javascript
// For - List rendering (recommended) <For each={items()}> {(item, index) => ( <div> {index()}: {item.name} </div> )} </For> // Index - Use index as key (better performance) <Index each={items()}> {(item, index) => ( <div> {index}: {item().name} </div> )} </Index>

Dynamic Components:

javascript
// Dynamic - Dynamic component rendering <Dynamic component={currentComponent()} props={props} /> // Portal - Portal to other DOM nodes <Portal mount={document.getElementById('modal-root')}> <Modal /> </Portal>

Suspense - Async Loading:

javascript
<Suspense fallback={<Loading />}> <AsyncComponent /> </Suspense> // Nested Suspense <Suspense fallback={<Skeleton />}> <Suspense fallback={<LoadingAvatar />}> <UserAvatar /> </Suspense> <Suspense fallback={<LoadingPosts />}> <UserPosts /> </Suspense> </Suspense>

ErrorBoundary - Error Boundary:

javascript
<ErrorBoundary fallback={(err) => <ErrorPage error={err} />}> <Component /> </ErrorBoundary>

Best Practices:

  • Use For instead of map for list rendering
  • Use Index when list item order doesn't change
  • Use Show for simple conditional logic
  • Use Switch for multiple condition branches
  • Use Suspense for async components
标签:SolidJS