动态选项不会触发SolidJS中的选择组件。 (包括游乐场)

问题描述 投票:0回答:1

我正在使用 SolidJS 和 SUID(Solid Material UI)库。

我正在尝试使用与 SUID 文档中相同的示例。

https://suid.io/components/select

import { For, createResource, createSignal } from 'solid-js';
import { Select, MenuItem } from '@suid/material'; // or "solid-ui", based on the library's exports

function Post() {
  const [postsResource, { mutate, refetch }] = createResource(async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  });

  // State for the selected option
  const [selectedOption, setSelectedOption] = createSignal('any');

  return (
    <div>
      <h1>Posts</h1>
      {postsResource.loading && <p>Loading...</p>}
      {postsResource.error && <p>Error: {postsResource.error.message}</p>}
      {
        <>
          <Select
            // defaultValue={'any'}
            // value={selectedOption()}
            onChange={(e) => {
              console.log('onChange', e.currentTarget);
              setSelectedOption(e.currentTarget.value);
            }}
          >
            <MenuItem value="any">Choose any...</MenuItem>
            <MenuItem value="option1">option1</MenuItem>
            <MenuItem value="option2">option2</MenuItem>
            <For each={postsResource()}>
              {(post) => <MenuItem value={post.id}>{post.title}</MenuItem>}
            </For>
          </Select>
        </>
      }
    </div>
  );
}

export default Post;

在这种情况下,具有

any
option1
option2
(静态选项)等值的选项是可选的,但其他选项则不可以。

我为您提供了stackblitz游乐场供您进行实验。

我还应该提到,当我使用静态选项(下面的代码)时,选择效果很好。

  const options = [
    {id: 1, label: 'Option 1'},
    {id: 2, label: 'Option 2'},
    {id: 3, label: 'Option 3'},
  ];

但是当我使用动态选项(fetch、

createResource
、promise 等)时,就会出现问题。 主要存在以下问题:

  1. 所选选项不会更改选择值
  2. onChange
    处理程序总是收到相似的值
  3. 超过两个 Select 更改会导致控制台错误:
MUI: A component is changing the uncontrolled value state of Select to be controlled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled Select element for the lifetime of the component.
The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.

我尝试:

  1. defaultValue
    设置为
    Select
  2. 设置一个
    defaultValue
    来创建信号;
  3. 设置一个
    tabIndex
    ,因为我注意到在
    For
    中每个
    MenuItem
    都有
    tabIndex=-1

tabIndex


我的期望是什么:

  • 我应该能够从“选择”中选择任何选项
material-ui signals solid-js suid
1个回答
0
投票

来自

createResource
的值将是
undefined
,直到请求解析为某个值。因此,组件
For
最初接收
undefined
。您应该相应地重组您的组件。最好使用带有resource.state值的Switch/Match来进行条件渲染。

© www.soinside.com 2019 - 2024. All rights reserved.