2016-09-24 125 views
0

我有2个阵营类:阵营的js SETSTATE使用阵营路由器

const PostList = React.createClass({ 
    getInitialState: function() { 
     return { 
      status: "loading", 
      posts: [] 
     } 
    }, 
    render: function() { 
     return (
     <div id="container"> 
      <ReactRouter.Link to="upload"></ReactRouter.Link> 
      <a href="#/upload">{this.state.status}</a> 
       { 
        this.state.posts.map(function (post) { 
         return (
          <Post post={post} /> 
         ); 
        }) 
       } 
      </div> 
     ); 
    } 
}); 

const Upload = React.createClass({ 
    render: function() { 
     return (
      <div className="upload">Upload</div> 
     ); 
    } 
}) 

const MainContent = React.createClass({ 
    render: function() { 
     return (
      <div> 
       <Header /> 
       <div id="inner-content"> 
        {this.props.children} 
       </div> 
       <Footer /> 
      </div> 
     ); 
    } 
}) 

const routes = (
    <Route path="/" component={MainContent}> 
     <ReactRouter.IndexRoute component={PostList} /> 
     <Route path="upload" component={Upload} /> 
    </Route> 
) 

var render = ReactDOM.render(<Router history={History}>{routes}</Router>, document.getElementById("content")); 

的问题是,我怎么能访问PostList的功能的setState呈现新的职位?

帖子将通过socket.io conenction被刷新,所以当一个新的职位到达时,我只是想设置PostList的状态重新呈现完整的HTML代码与他的新博文

对不起坏英语...

回答

1

添加componentDidMount功能,并建立了一个套接字监听里面,这样当新邮件到达时,将其添加到帖子

const PostList = React.createClass({ 
    getInitialState: function() { 
     return { 
      status: "loading", 
      posts: [] 
     } 
    }, 
    componentDidMount: function() { 
     var that = this; 
     // Be sure to set up data fetching code here 

     // Set up listener for posts updates here 
     socket.on('update', function (data) { 
      // Assuming data contains the post content 
      that.setState({ 
       posts: that.state.posts.concat(data) 
      }); 
     }); 
    }, 
    render: function() { 
     return (
     <div id="container"> 
      <ReactRouter.Link to="upload"></ReactRouter.Link> 
      <a href="#/upload">{this.state.status}</a> 
       { 
        this.state.posts.map(function (post) { 
         return (
          <Post post={post} /> 
         ); 
        }) 
       } 
      </div> 
     ); 
    } 
}); 
+0

它现在的工作的当前列表,谢谢! 但是当我导航到上传并返回到主页面(不刷新)(显示帖子列表)为什么该列表不能识别我的帖子?所以当我导航没有刷新页面的帖子是空的再次... 我做错了什么? – MSzucs

+2

如果它帮助你,接受我的答案? (: 因为当你从那个页面离开时,组件被卸载,那么呈现的DOM元素将被移除并替换为你的上传页面,当你返回页面时,将不会有数据。在'componentDidMount()'开始实现一个数据获取调用来获取已有的数据,'socket.on('update')'方法只会告诉你的组件有新的帖子;它不会获取现有的帖子。 –

+0

@MSzucs我已经更新了我的答案,告诉你在哪里设置数据获取代码。 –