反应选择选项更新给出[对象承诺]

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

我在代码中使用 React Select 并尝试根据输入更新选项,但是即使在触摸选择框之后,我也面临着 [object Promise] 作为输入中的值的问题。下面是我的代码。

<tbody>
  {filteredResults && filteredResults.length > 0 ? (
    filteredResults.map((data) => (
      <React.Fragment key={data.id}>
        <tr>
          <td>{data.name}</td>
          <td>
            <form
              onSubmit={(e) => handleSubmit(e, data)}
              style={{ display: "flex", alignItems: "center" }}
            >
              <input
                type="text"
                className="form-control"
                value={data.alias}
                name="alias"
                onChange={(e) => handleAliasChange(data.id, e.target.value)}
              />
              <input type="hidden" name="name" value={data.name} />
              <input type="hidden" name="key" value={data.key} />
              &nbsp;
              {/* Country select field */}
              <Select
                options={countryOptions}
                name="player_country"
                onChange={(selectedOption) =>
                  handleCountryChange(selectedOption, data.id)
                }
                placeholder="Select Country"
              />
              &nbsp;
              {/* Entity Name field (shown after country is selected) */}
              {data?.showEntityField && (
                <>
                  {console.log(data?.entityResults)}
                  <Select
                    name="entity_key"
                    options={data?.entityResults ?? []} // It will show the search results
                    onInputChange={(query) => handleSearch(query, data.id)} // Search when user types
                    placeholder="Search Entity Name"
                    // value={data?.searchQuery ?? ""} // Show typed query as value
                    // onChange={(selectedOption) => handleEntityChange(selectedOption, data.id)} // Handle when an option is selected
                    noOptionsMessage={() => "No options available"}
                  />
                </>
              )}
              &nbsp;
              <button type="submit" className="btn btn-primary mt-2">
                Submit
              </button>
            </form>
          </td>
        </tr>
      </React.Fragment>
    ))
  ) : (
    <tr>
      <td colSpan="3">No result to display</td>
    </tr>
  )}
</tbody>;

JSX 的功能为

const handleSearch = async (query, id) => {
  let country = null;
  const foundData = filteredResults.find((data) => data.id === id);

  if (foundData) {
    country = foundData.country;
  }

  if (country) {
    try {
      const data = await searchPlayers(country, query);

      if (data.status === 200) {
        const results = data.data.response.items.map((item) => ({
          value: item.pid,
          label: `${item.title} (DOB: ${item.birthdate ?? "N/A"})`,
        }));

        // Update the specific player's searchQuery and entityResults
        const updatedResults = filteredResults.map((player) => {
          if (player.id === id) {
            return { ...player, searchQuery: query, entityResults: results }; // Update query + results
          }
          return player;
        });

        setFilteredResults(updatedResults); // Set updated results
      } else {
        console.error("API response error");
      }
    } catch (error) {
      console.error("Error fetching entity data:", error);
    }
  } else {
    console.log("No country found for the selected player.");
  }
};

在handleSearch上我尝试调用api并搜索相关的玩家列表。但这是多么麻烦啊,列表已更新,但它在输入中显示[对象承诺],整个主体变得混乱。出现白色页面。

reactjs react-select react-select-search
1个回答
0
投票

是的,所以我得到了答案,因为 React Select 确实服务于 Promises。因此,在获取新列表时,选项将被追加并采用异步方法。

import AsyncSelect from 'react-select/async';

<AsyncSelect
    cacheOptions
    defaultOptions
    className="form-control"
    loadOptions={(inputValue) => handleSearch(inputValue, data.id)}
    onChange={(selectedOption) => handleEntityChange(selectedOption, data.id)}
    value={data?.selectedEntity || null}
    placeholder="Search Entity Name"
    noOptionsMessage={() => 'No options available'}
/>

所以这里我们需要 React Async Select。

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