ES6 数组映射不返回任何内容:ReactJS

IT技术 javascript reactjs ecmascript-6
2021-03-23 02:53:18

我有一个数组,我有一个简单的字符串值。我想映射我的数组,因为我试图找到我的字符串值。

我有这样的代码,但 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'));
2个回答

因为您没有从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> ); 
}

建议:

为每个元素分配唯一

查看此答案以获取有关 key 的更多详细信息:Understanding unique keys for array children in React.js

你应该返回map函数本身,你也可以用es6单线箭头函数来实现它

class Application extends React.Component {
  constructor(){
    super();

    this.state = {
      questionAnswer: 'is that possible',
      question: ['is', 'possible', 'that']
    }  
  }

  renderKeywords() {
    return this.state.question.map((item, i) =><span key={i}>{item}
   </span>}); 
  }

  render() {
    return (
      <div>
        <div>blabla</div>
        {this.renderKeywords()}  
      </div>
   );
 }
}
React.render(<Application />, document.getElementById('app'));
你的回答并没有给这个问题带来任何新的东西,基本上只是在重复已经接受的答案......
2021-05-29 02:53:18
我已经更新了 es6 箭头函数,当你直接从它返回一些东西时,它是它的实际实现。@MarekTakac
2021-06-17 02:53:18