reactjs - 将工作和功能性 reactjs 组件转换为基于类的组件
问题描述
我试图弄清楚如何在 Visual Studio 2017 环境中转换这个功能性 React 组件并使用 ASP.Net MVC 框架下面的代码可以正常工作:
var ProductGridRow = React.createClass({
render : function(){
return (
<tr>
<td>{this.props.item.ProductName}</td>
<td>{this.props.item.Price}</td>
</tr>
);
}
});
var ProductGridTable = React.createClass({
getInitialState: function(){
return {
items:[]
}
},
componentDidMount:function(){
// Fetch data via ajax *@
$.get(this.props.dataUrl, function(data){
if(this.isMounted()){
this.setState({
items: data
});
}
}.bind(this));
},
render : function(){
var rows = [];
this.state.items.forEach(function(item){
rows.push(
<ProductGridRow key={item.Id} item={item} />);
});
return (
<table className="table table-bordered table-responsive">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>);
}
});
ReactDOM.render(
<ProductGridTable dataUrl="/home/getProductData" />,
document.getElementById('griddata')
);
但是,当我尝试将上述代码转换为具有符合当前实践的基于类的组件时,并且当我尝试这样做时:
class ProductGridRow extends React.Component {
constructor(props) {
super(props);
this.state = {
productRow: []
}
render()
{
return (
<tr>
<td>{this.props.item.ProductName}</td>
<td>{this.props.item.Price}</td>
</tr>
);
}
}
}
class ProductGridTable extends React.Component {
constructor(props) {
super(props);
this.state = {
productList: []
};
this.loadData = this.loadData.bind(this);
}
componentDidMount(){
// Fetch data via ajax
this.loadData();
}
loadData() {
$.get(this.props.dataUrl,
function(data) {
if (this.isMounted()) {
this.setState({
items: data
});
}
});
}
render(){
var rows = [];
this.state.productList.forEach(function(item) {
rows.push(
<ProductGridRow key={item.Id} item={item}/>);
})
return (
<table className="table table-bordered table-responsive">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>);
}
}
ReactDOM.render(<ProductGridTable dataUrl="/home/getProductData" />
,document.getElementById('griddata'));
但它以“Uncaught TypeError: this.isMounted is not a function”告终。不确定转换后应该是正确的代码。有人可以帮忙吗?
解决方案
isMounted
已弃用。只需将if (this.isMounted()) {...}
调用周围的块删除到setState
AJAX 成功处理程序回调内部即可。
https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
推荐阅读
- python - 从 16 位宽寄存器中选择一个引脚,python
- vb.net - 反序列化来自 API 的非 xml 或 json 响应
- scala - 在 spark 数据集中加入两个聚簇表似乎最终会完全洗牌
- javascript - ThreeJS-添加bloom pass会影响画布透明度
- visual-studio-code - VS Code Windows 10:LaTeX Workshop 无法编译
- ffmpeg - ffmpeg 后台多进程
- elasticsearch - ES 下面的字段如何匹配&在特定情况下不删除令牌?
- algorithm - 在数组中的前 N 个数字中找到最大数字的有效方法
- python - 带有 keras 的 CNN 给出了 Graph disconnected 错误
- verilog - Verilog:错误引用标量线'VALUE'不是合法的reg或变量左值