javascript - ReactJS - 使用 map 循环遍历数据数组 Prop 时遇到问题

标签 javascript reactjs

第一次使用 ReactJS,在循环通过 AJAX 检索到的数据进行填充时遇到问题。我收到许多错误,包括 Uncaught TypeError: Cannot read property 'map' of undefined。我应该设置 Prop 还是状态?

var Posts = React.createClass({
getInitialState: function() {
     return ({
        posts: []
     })
},

loadPosts: function(){
    var posts = null;
    axios.get('/getposts')
      .then(function (result) { 
        posts = result.data;    
      })
      .catch(function (error) {
        console.log(error);
      });
},

postReadMode: function() {
    return (
        <div>
        </div>
    )
},

render: function() {
    return (
        <div>
            Hello, {this.props.posts.map(function(item, i){
                return item.title;
            })}
        </div>
    )
}

})

返回的数据有点像多维对象/数组:

Obj:
  0: 
     title: 'Title 1',
     date: '12-2-2015',
     content: 'asdf'
  1: 
     title: 'Title 2',
     date: '1-25-2016',
     content: 'asdfasdf'

最佳答案

有两点我们需要澄清:

  • 使用 {this.props.posts.map(..)是不正确的。 posts (在本例中)是 state因为它的值已更改(在 AJAX 请求后从 [] 更改为 AJAX response)。您必须使用{this.state.posts.map(...)render方法。

  • 您应该在 componentDidMount 内实现 AJAX 调用方法:

If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

componentDidMount: function() {
    var self = this;
    axios.get('/getposts')
        .then(function (result) { 
            self.setState({
                posts: result.data
            });
        })
        .catch(function (error) {
            console.log(error);
        });
}

设置setState方法将更改 posts状态值,因此 render方法将再次运行以显示新的 UI。

如果您想要更好的方法来处理异步网络内容,请尝试 Redux AsyncActions .

关于javascript - ReactJS - 使用 map 循环遍历数据数组 Prop 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42149663/

相关文章:

javascript - 将 "this"与另一个外部函数一起使用

javascript - Vuejs 使用方法发送 GET 请求

c# - 将加载指示器添加到谷歌地图 infoWindow

regex - 为什么react-router正确处理正则表达式 `path`,但同时抛出错误?

reactjs - 如何在页面重新加载时重置 react 路由器

javascript - 将元素添加到 react 列表中的列表中

javascript - SPA 在路由更改时将存储值重置为默认值

javascript - 使用拖放时如何在服务器端获取新的 GridView 行顺序?

reactjs - 使用语义 UI react 预填充输入文本

reactjs - 如何在 React 应用程序中模拟 linux 终端