【问题标题】:ES6 array map doesn't return anything: ReactJSES6 数组映射不返回任何内容:ReactJS
【发布时间】:2017-08-14 08:26:12
【问题描述】:

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

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

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

因为你没有从renderKeywords 方法返回任何东西,你只是从地图主体返回。如果你没有从函数中返回任何东西,那么默认情况下它会返回undefined,你需要返回map的结果(元素数组)。

像这样:

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

【讨论】:

    【解决方案2】:

    你应该返回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'));
    

    【讨论】:

    • 你的回答并没有给问题带来任何新的东西,基本上只是重复已经接受的答案......
    • 我更新了 es6 箭头函数,当你直接从它返回一些东西时,它是它的实际实现。 @MarekTakac
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2019-04-14
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多