React中return语句无法渲染组件问题求助
问题原因与解决方法
核心问题出在你用了forEach遍历数组——forEach没有返回值,它仅执行回调函数,最终返回undefined,所以这段JSX本质上是在渲染undefined,页面自然看不到内容。
把forEach替换成map就能解决,因为map会返回新数组,数组里包含回调中返回的JSX元素,React可以正常渲染这个数组。
修改后的代码:
{newData?.data.map((x: any, index: number) => { return Object.keys(x).map((key: any) => { console.log(key) return ( <Grid item xs={12} key={`${index}-${key}`}> <TextField style={{ width: "100%" }} required label={key} onChange={handleOnchange(key)} /> </Grid> ) }) })}
额外提示:
- 别用数组索引
_i作为key,嵌套遍历场景下,用${外层索引}-${key}这类组合键更稳定,避免React渲染时出现组件复用错误。 - 确认
newData?.data确实是数组,且每个x对象存在可遍历的键。
内容的提问来源于stack exchange,提问作者NOK
相关产品推荐
相关产品推荐

