ES6数组映射不返回任何内容:ReactJS [英] ES6 array map doesn't return anything: ReactJS

查看:105
本文介绍了ES6数组映射不返回任何内容:ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array and i have a simple string value. I want to mapping my array because i'm try to find my string value.

我有这样的代码,但map函数不会返回任何内容:/

I have a code like this, but map function doesn't return anything :/

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'));


推荐答案

因为你没有从<$ c $返回任何东西c> renderKeywords 方法,您只从地图主体返回。如果你没有从函数返回任何东西,那么默认它将返回 undefined ,你需要返回map的结果(元素数组)。

Because you are not returning anything from renderKeywords method, you are returning from map body only. If you don't return anything from function then by default it will return undefined, you need to return the result of map (array of elements).

喜欢这样:

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 到每个元素。

Assign unique key to each element.

检查此答案以获取有关密钥的更多详细信息:了解React.js中数组子项的唯一键

Check this answer for more details about key: Understanding unique keys for array children in React.js

这篇关于ES6数组映射不返回任何内容:ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆