Javascript 使用{}在map()中使用时不呈现元素
当我使用这种形式的代码时,React不会呈现元素:Javascript 使用{}在map()中使用时不呈现元素,javascript,arrays,reactjs,ecmascript-6,arrow-functions,Javascript,Arrays,Reactjs,Ecmascript 6,Arrow Functions,当我使用这种形式的代码时,React不会呈现元素: class ListaPratitelja extends React.Component { constructor(props) { super(props); } render() { const items = this.props.pratitelji; const listItems = items.map((name, index) => {
class ListaPratitelja extends React.Component {
constructor(props) {
super(props);
}
render() {
const items = this.props.pratitelji;
const listItems = items.map((name, index) => {
e(Pratitelj, { key: index, name: name });
});
return listItems;
}
}
我使用了一个调试器来查看发生了什么,而e函数(只是React.createElement)返回未定义的
但当我这样使用它时,它工作得很好:
class ListaPratitelja extends React.Component {
constructor(props) {
super(props);
}
render() {
const items = this.props.pratitelji;
const listItems = items.map((name, index) => e(Pratitelj, { key: index, name: name }));
return listItems;
}
}
问题是为什么?这是一个bug还是我在第一个示例中做错了什么。这也是完整的代码:
'use strict';
const e = React.createElement;
class ListaPratitelja extends React.Component {
constructor(props) {
super(props);
}
render() {
const items = this.props.pratitelji;
const listItems = items.map((name, index) => e(Pratitelj, { key: index, name: name }));
return listItems;
}
}
class Pratitelj extends React.Component {
constructor(props) {
super(props);
this.state = { deleted: false };
this.handleDeleteChange = this.handleDeleteChange.bind(this);
}
handleDeleteChange(deletedState) {
this.setState({ deleted: deletedState });
}
render() {
console.log("rendered");
if (this.state.deleted) {
return '';
}
return e(
'div',
null,
e(PratiteljIme, { name: this.props.name }),
e(PratiteljDeleteButton, { handleDeleteChange: this.handleDeleteChange})
);
}
}
class PratiteljIme extends React.Component {
constructor(props) {
super(props);
}
render() {
return e(
"span",
null,
this.props.name)
}
}
class PratiteljDeleteButton extends React.Component {
constructor(props) {
super(props);
}
render() {
return e(
"button",
{ type: "button", "onClick": this.props.handleDeleteChange},
"X"
)
}
}
function loadListaPratitelja(pratitelji) {
const lista = pratitelji.split(",");
const domContainer = document.querySelector('#listaPratitelja');
ReactDOM.render(e(ListaPratitelja, {pratitelji: lista}), domContainer);
}
输入变量“pratitelji”只是一个带有两个CSV的字符串(例如p1、p2、p3、p4)。
我使用的react版本如下:
我测试的浏览器是firefox for development的最新版本。使用
{
和}
创建的函数不会返回任何内容,除非返回一些内容。因此,.map
将返回一个填充了未定义的数组
将您的代码更新为:
const listItems = items.map((name, index) => {
return e(Pratitelj, { key: index, name: name });
});
如果在箭头后打开函数,则必须说明返回的内容。不带主体的箭头函数将隐式返回一个且唯一的表达式,而带主体的箭头函数将隐式返回一个()=>{…}
类似于任何其他函数,因为您需要显式地返回它的值。