我有一个数组,我有一个简单的字符串值。我想映射数组,因为我试图找到我的字符串值。
我有这样的代码,但是map函数不返回任何内容:/
class Application extends React.Component { constructor(){ super(); this.state = { questionAnswer: 'is that possible', question: ['is', 'possible', 'that'] } } renderKeywords() { this.state.question.map((item, key) => { return ( <span>{item}</span> ); }); } render() { return ( <div> <div>blabla</div> {this.renderKeywords()} </div> ); } } React.render(<Application />, document.getElementById('app'));
由于您没有从renderKeywords方法返回任何内容,因此仅从地图正文返回。如果您不从函数返回任何内容,则默认情况下它将返回undefined,您需要返回map(元素数组)的结果。
renderKeywords
undefined
像这样:
renderKeywords() { return this.state.question.map((item, key) => { //here return ( <span key={key}> {item} </span> ); }); }
简而言之,您可以这样编写:
renderKeywords() { return this.state.question.map((item, key) => <span key={key}> {item} </span> ); }
建议:
为每个元素分配唯一 键 。