Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 将数组值显示到react js中的选择选项标记中_Reactjs - Fatal编程技术网

Reactjs 将数组值显示到react js中的选择选项标记中

Reactjs 将数组值显示到react js中的选择选项标记中,reactjs,Reactjs,我试图在select标记中显示数组值,但所有数组值都显示为单个值。请看下面我添加的逻辑。数据是动态的,我从后端获取的数据如下[“Sankranti”,“Sankranti 1”] const[eventNameList,setEventNameList]=useState([]) var eventList=eventNameList.length>0? eventNameList.map((项目,i)=>{ console.log('list:',项) 返回( {item} ) }) : “无

我试图在select标记中显示数组值,但所有数组值都显示为单个值。请看下面我添加的逻辑。数据是动态的,我从后端获取的数据如下[“Sankranti”,“Sankranti 1”]

const[eventNameList,setEventNameList]=useState([])
var eventList=eventNameList.length>0?
eventNameList.map((项目,i)=>{
console.log('list:',项)
返回(
{item}
)
})
:
“无事件”
{eventList}
请查看下面的控制台屏幕截图


看起来您的列表嵌套在另一个
数组中
,因此要解决此问题,您可以使用而不是
映射

或者您可以在嵌套的
数组中迭代抛出第一个
元素

const [eventNameList, setEventNameList] = useState([])

var eventList = eventNameList.length > 0 ? 
                eventNameList[0].map((item,i) => {
                    console.log('list: ', item)
                    return (
                        <option>{item}</option>
                        )
                    })
                    :
                    'No Events'
<select>
      {eventList}
</select>
const[eventNameList,setEventNameList]=useState([])
var eventList=eventNameList.length>0?
eventNameList[0]。映射((项,i)=>{
console.log('list:',项)
返回(
{item}
)
})
:
“无事件”
{eventList}

能否在循环外部打印
事件名称列表
并显示结果?我认为您的结果是嵌套数组,这就是为什么要在循环中获得数组。你能给我们看看你从api.outside循环返回的结果吗?我添加了eventNameList。它像这样显示在控制台中。eventNameList:[Array(2)]0:[2][“Sankranti”,“Sankranti 1”]长度:1 proto:Array(0)我得到了与以前相同的结果。请尝试此结果,而不是
flatMap
try
eventNameList[0]。map
感谢此逻辑eventNameList[0]。map工作正常。您能告诉我这个逻辑是如何工作的吗?不客气:),因为它返回一个子数组,其中包含
[[“Sankranti”,“Sankranti 1”],“另一个您不需要的数据”]
,所以您只需要第一个索引中包含您的
数组的列表,这样您就可以通过外部数组库中的索引访问它,知道了。
const [eventNameList, setEventNameList] = useState([])

var eventList = eventNameList.length > 0 ? 
                eventNameList[0].map((item,i) => {
                    console.log('list: ', item)
                    return (
                        <option>{item}</option>
                        )
                    })
                    :
                    'No Events'
<select>
      {eventList}
</select>