如何在ReactJS的模型更改中触发重新渲染?
问题描述:
我创建一个使用如何在ReactJS的模型更改中触发重新渲染?
React.render(<ReactComponent data="myData">, document.body);
一旦数据模型的变化作出反应成分,我称之为渲染再次使用
React.render(<ReactComponent data="myData">, document.body);
是更新我的HTML这个正确的/推荐的方法是什么?
这是否会利用React虚拟DOM的优势(即只渲染实际更改的元素)。
此外,我应该在传递myData时使用状态或属性?
答
您应该只渲染一个主要的应用程序组件,它执行AJAX请求等,并使用其渲染函数内的数据模型来更新子组件。
创建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);
谢谢!我确实读过,我只是有点困惑。感谢澄清。 –