使用React Router反应Js SetState

时间:2016-09-24 11:23:39

标签: javascript reactjs react-router

我有2个React Classes:

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 个答案:

答案 0 :(得分: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>
        );
    }
});