在React中显示逗号分隔的数组元素

sug*_*yal 2 jsx reactjs

 class App extends Component {
    constructor(props){
    super(props);
    this.state={ recipes :[] } 
    this.addRecipe=this.addRecipe.bind(this);
    }

    addRecipe (recipe) {
    console.log({...recipe})
      this.setState({ 
      recipes: [...this.state.recipes, recipe]
    });
    }
    componentWillMount(){
    this.setState({
      recipes : require('./sample-recipes')
    });
    } 
    render() {
    return (
      <div className="App">
      <h2>Welcome to the Recipe Book</h2>
      <dl>
      {this.state.recipes.map(recipe => {
        return ( <div key={recipe.name}>
                 <dt>{recipe.name}</dt>
                 <dd>{recipe.ingredient}</dd>
                 <hr></hr>
                 </div>
                 )
      })
     }
      </dl>
     <button className="addButton" onClick={() => 
      {this.setState({ display: !this.state.display })}}>
     Add Recipe
     </button>
     <AddRecipe addRecipe={this.addRecipe} 
     display={this.state.display} />
     </div>
     );
     }

}
Run Code Online (Sandbox Code Playgroud)

我的sample-recipe.js文件如下

module.exports = [ 
{
name : 'chicken',
ingredient : ['spinach','chillies']
  }];    
Run Code Online (Sandbox Code Playgroud)

嗨,我是React的新手.我正在制作这个食谱书项目.我想显示以空格或逗号分隔的成分.现在它显示为"spinachchillies".这是一种将成分制成阵列的正确方法吗?

Shu*_*tri 6

由于成分是array of strings你可以join创建一个字符串并显示结果

{this.state.recipes.map(recipe => {
        return ( <div key={recipe.name}>
                 <dt>{recipe.name}</dt>
                 <dd>{recipe.ingredient.join(",")}</dd>
                 <hr></hr>
                 </div>
                 )
      })
     }
Run Code Online (Sandbox Code Playgroud)