[英]React component do not gets updated after changing the the state in componentDidMount
I'm working on a react component that render a table with some data coming down from an API on the server as follows: 我正在处理一个react组件,该组件使用来自服务器上API的一些数据来呈现表,如下所示:
var ModulesTable = React.createClass({ getInitialState: function () { return { modules: "" }; }, componentDidMount: function () { var get = $.get("/api/Modules/GetModules") .done(function (results) { if (results != null) { var rows = results.map((module) => { var statusImg; if (module.IsActive) statusImg = <a><i className="ti-check"></i></a>; return (<tr> <td>{module.ModuleId}</td> <td>{module.ModuleName}</td> <td>{statusImg}</td> </tr>); } ); this.setState({ modules: rows }); } } .bind(this)) .fail(function (err) { alert(err); }); }, render: function () { return (<table className="table table-striped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Used</th> </tr> </thead> <tbody> {this.state.modules} </tbody> </table>); } }); ReactDOM.render( <ModulesTable />, document.getElementById("tableContainer"));
The problem is the component is not gets updated with the data returned from the API and the console show no signs of any error plus the API is working fine. 问题在于该组件未使用从API返回的数据进行更新,并且控制台未显示任何错误的迹象,并且该API工作正常。 I suspect that the problem with setState probably. 我怀疑setState可能存在问题。 what i'm doing wrong here? 我在这里做错了什么?
this
does not work with jQuery xhr callbacks
. this
不适用于jQuery xhr callbacks
。 Just try this instead 只要试试这个
const self = this;
var get = $.get("/api/Modules/GetModules")
.done(function (results) {
if (results != null) {
var rows = results.map((module) => {
var statusImg;
if (module.IsActive)
statusImg = <a><i className="ti-check"></i></a>;
return
(<tr>
<td>{module.ModuleId}</td>
<td>{module.ModuleName}</td>
<td>{statusImg}</td>
</tr>);
}
);
self.setState({
modules: rows
});
}
}
.bind(this))
.fail(function (err) {
alert(err);
});
I've found a solution by getting rid of map function and use the regular for loop fixed my problem as following : 我已经找到摆脱地图功能的解决方案,并使用常规的for循环解决了我的问题,如下所示:
componentDidMount: function () {
var get = $.get("/api/Modules/GetModules")
.done(function (results) {
if (results != null) {
var rows = [];
for (var i = 0; i < results.length; i++) {
var module = results[i];
if (module.IsActive) {
rows.push(
<tr>
<td>{module.ModuleId}</td>
<td>{module.ModuleName}</td>
<td><a><i className="ti-check"></i></a></td>
</tr>
);
}
else {
rows.push(
<tr>
<td>{module.ModuleId}</td>
<td>{module.ModuleName}</td>
<td><a><i className="ti-close"></i></a></td>
</tr>
);
}
}
this.setState({
modules: rows
});
console.log(rows);
}
}.bind(this))
.fail(function (err) {
alert(err);
});
}
this.state.modules
而不是modules
,请参见演示@ https://jsfiddle.net/wv3yopo0/2674/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.