list.map 未显示在 React 组件中

IT技术 reactjs
2021-05-11 14:33:36

我正在尝试在视图中获取此列表,但这不显示任何项目

render: function() {
    var list = this.state.list;
    console.log('Re-rendered');
    return(
        <ul>
        {list.map(function(object, i){
            <li key='{i}'>{object}</li>
        })}
        </ul>
    )
}

list首先设置为空,然后我用 AJAX 重新加载它。另一方面,这有效

    <ul>
    {list.map(setting => (
        <li>{setting}</li>
    ))}
    </ul>

这是我的整个组成部分:

var Setting = React.createClass({
   getInitialState: function(){
     return {
       'list': []
     }
   },
   getData: function(){
     var that = this;
     var myHeaders = new Headers();
     var myInit = { method: 'GET',
           headers: myHeaders,
           mode: 'cors',
           cache: 'default' };
    fetch('/list/',myInit)
        .then(function(response){
            var contentType = response.headers.get("content-type");
            if(contentType && contentType.indexOf("application/json") !== -1) {
            return response.json().then(function(json) {
                that.setState({'list':json.settings});
            });
            } else {
            console.log("Oops, we haven't got JSON!");
            }

        })
        .catch(function(error) {
            console.log('There has been a problem with your fetch operation: ' + error.message);
        });;    
   },
   componentWillMount: function(){
    this.getData();
   },
   render: function() {
    var list = this.state.list;
    return(
        <ul>
        {list.map(function(object, i){
            <li key={i}>{object}</li>
        })}
        </ul>
    )
  }
});
1个回答

您缺少退货声明

 {list.map(function(object, i){
   return <li key={i}>{object}</li>
 })}

这有效

  <ul>
    {list.map(setting => (
        <li>{setting}</li>
    ))}
   </ul>

因为()使用箭头函数时会自动返回其中的任何内容,但前面的示例使用的{}是需要 return 语句。

我什么时候应该在 es6 箭头函数中使用 `return`?这将为您提供有关何时以及何时不使用带有箭头函数的 return 语句的更多上下文。