在React中如何遍历C# Web API返回的食材字符串并渲染为<ul>列表
你可以先按后端存储ingredients字符串的分隔规则将其拆分为数组,再遍历渲染为列表,具体实现如下:
步骤1:确认分隔规则
首先明确你后端存储ingredients的字符串分隔标识,常见的有英文逗号、换行符、分号等。例如存储格式为"鸡蛋,低筋面粉,纯牛奶,白砂糖"时,分隔符为英文逗号。
步骤2:修改Recipe组件代码
将原组件中直接渲染ingredients字符串的逻辑,替换为拆分后遍历渲染列表的逻辑,完整修改后的代码如下:
import React from 'react'; import PropTypes from 'prop-types'; function Recipe(props) { // 拆分食材字符串为数组,可根据你的实际分隔符替换split内的参数 const ingredientList = props.ingredients.split(',') .map(item => item.trim()) .filter(item => item.length > 0); return ( <React.Fragment> <img src={props.recipeImage} alt='食谱图片' className='recipePicture'></img> <h1>{props.name}</h1> <h3><strong>分类:</strong> {props.category}</h3> <h3><strong>菜系:</strong> {props.cuisine}</h3> <h4><strong>食材:</strong></h4> <ul> {ingredientList.map((ingredient, index) => ( <li key={index}>{ingredient}</li> ))} </ul> <h4><strong>总耗时:</strong> {props.time}</h4> <h4><strong>份量:</strong> {props.makes}</h4> <h4><strong>步骤:</strong> {props.instructions}</h4> </React.Fragment> ) } Recipe.propTypes = { recipeImage: PropTypes.string, name: PropTypes.string, category: PropTypes.string, cuisine: PropTypes.string, ingredients: PropTypes.string, time: PropTypes.string, makes: PropTypes.number, instructions: PropTypes.string, recipeId: PropTypes.number } export default Recipe;
补充说明
如果你的分隔符不是英文逗号,可自行修改split方法内的参数:
- 若为换行分隔:改为
.split('\n') - 若为分号分隔:改为
.split(';')
后续如果后端调整为直接返回string[]类型的ingredients,直接删除split拆分的步骤,直接遍历返回的数组即可,同时可将propTypes里的ingredients校验规则改为PropTypes.arrayOf(PropTypes.string)。
内容的提问来源于stack exchange,提问作者jjisnewbutdevelops
相关产品推荐
相关产品推荐

