繁体   English   中英

如何在ReactJS中触发模型更改的重新渲染?

[英]How to trigger re-render on model change in ReactJS?

我正在使用创建反应组件

React.render(<ReactComponent data="myData">, document.body);

一旦数据模型改变,我再次使用调用render

React.render(<ReactComponent data="myData">, document.body);

这是更新我的HTML的正确/推荐方式吗?
这会利用React虚拟DOM的优势(即仅渲染实际已更改的元素)。

另外,我在传递myData时应该使用状态还是属性?

您应该只渲染一个执行AJAX请求等的主要App组件,并使用其render函数内的数据模型来更新子组件。

在创建React组件时,您应始终保持使用状态最小值并将其移至顶级组件,而应使用props来呈现子组件。

当我第一次开始使用React时,这篇文章给了我很多帮助: https//github.com/uberVU/react-guide/blob/master/props-vs-state.md

像这样的东西:

var App = React.createClass({
    render: function(){
        return (
            <div>
                <input type="button" onClick={this.handleClick}/>
                <Dropdown items={this.state.countries}/>
            </div>
        )
    },
    getInitialState: function(){
        return {countries: {}};
    },
    componentDidMount: function(){
        var self = this;
        $.getJSON("countries", function(err, countries){
            self.setState({countries: countries});
        });
    },
    handleClick: function(){
        // every time the user does something, 
        // all you need to do is to update the state of the App 
        // which is passed as props to sub components
    }
})

React.render(React.createElement(App, {}), document.body);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM