【问题标题】:Data did not populate in select option tag in REACTJS数据未填充到 REACTJS 的选择选项标记中
【发布时间】:2021-06-17 06:39:44
【问题描述】:

我想动态填充<select> <option> 中的响应数据。

示例数据:

{
   "uuid":"123123",
   "car_manufacturer":"Audi",
   "models":[
      {
         "car_model":"model_name",
         "uuid":"213"
      },
      {
         "car_model":"model_name",
         "uuid":"213"
      }
   ]
}

我只想在选择选项中映射 models 数组。

这是我目前尝试过的:

 const [model, setModel] = useState([]);

   {model ?
          <>
            { model.models.map((item, i) => (
               <option key={i} value={i} >
               {item.car_model}
               </option>
             ))}
             </> :
             <>
             <div>Loading...</div>
             </>}

错误出现

TypeError: model.map is not a function

【问题讨论】:

  • 首先模型是一个对象而不是数组,所以它应该是useState({}) 或类似的东西。另外,你能console.logmodel 看看它打印了什么吗?
  • console.log 显示我上面提到的示例数据
  • 我使用 useEffect 从 API 获取响应并设置状态和 useState({}) 仍然无法正常工作
  • ok 找到了问题。发布我的答案

标签: node.js reactjs react-native react-hooks


【解决方案1】:

您将 model 对象初始化为一个空数组

const [model, setModel] = useState([]);

所以model ? 将是真的,尽管它不会在未知属性中找到models 属性或map 函数。

将您的 model 初始化为 undefinednull 并检查代码中的 models 属性

因此,我建议进行以下更改:

const [model, setModel] = useState(null);

{ model && model.models ?

【讨论】:

    猜你喜欢
    • 2019-11-24
    • 2020-05-11
    • 2022-01-03
    • 2016-11-18
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多