ES6 数组映射不返回任何内容:ReactJS [英] ES6 array map doesn't return anything: ReactJS
问题描述
我有一个数组,我有一个简单的字符串值.我想映射我的数组,因为我试图找到我的字符串值.
我有这样的代码,但 map 函数不返回任何内容:/
class Application 扩展 React.Component {构造函数(){极好的();this.state = {questionAnswer: '这可能',问题:['是','可能','那个']}}渲染关键字(){this.state.question.map((item, key) => {返回 (<span>{item}</span>);});}使成为() {返回 (<div><div>blabla</div>{this.renderKeywords()}
);}}React.render(
因为您没有从 renderKeywords
方法返回任何内容,所以您只是从地图主体返回.如果你不从函数返回任何东西,那么默认情况下它会返回undefined
,你需要返回map的结果(元素数组).
像这样:
renderKeywords() {return this.state.question.map((item, key) => {//这里返回 (<span key={key}>{item} </span>);});}
简而言之,你可以这样写:
renderKeywords() {return this.state.question.map((item, key) => {item} );}
建议:
分配唯一的key 到每个元素.
查看此答案以了解有关密钥的更多详细信息:Understanding uniqueReact.js 中数组子项的键
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.
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'));
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).
Like this:
renderKeywords() {
return this.state.question.map((item, key) => { //here
return (
<span key={key}> {item} </span>
);
});
}
In short you can write it like this:
renderKeywords() {
return this.state.question.map((item, key) => <span key={key}> {item} </span> );
}
Suggestion:
Assign unique key to each element.
Check this answer for more details about key: Understanding unique keys for array children in React.js
这篇关于ES6 数组映射不返回任何内容:ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!