我有一个列表 zones
,我要显示。
现在我创建了一个简单的测试。单击按钮,应将虚拟条目添加到列表中。变量正在更新,但列表组件不显示新条目。
这是我的代码:
import React, { Component } from 'react';
import FreightList from './FreightList';
import ZoneList from './ZoneList';
class FreightCapture extends Component {
constructor(props) {
super(props);
this.state = {
freights: props.freights,
zones: [{ID:"1",Fracht_ID:"2",Gebiet_von:"test"}],
freightListId: 1,
zoneListId: 2
};
}
testOnClick(event) {
event.preventDefault();
let newEntry = [{ID:"2",Fracht_ID:"2",Gebiet_von:"test test"}];
this.setState({
zones: this.state.zones.concat(newEntry)
})
}
render() {
return (
<div>
<FreightList freights={this.state.freights} parent={this} key={this.state.freightListId} />
<ZoneList zones={this.state.zones} key={this.state.zoneListId} />
<button onClick={this.testOnClick.bind(this)}>Test</button>
</div>
);
}
}
export default FreightCapture
ZoneList.js:
import React, { Component } from 'react';
import Zone from './Zone';
class ZoneList extends Component {
constructor(props) {
super(props);
this.state = {
zones: props.zones
};
}
handleFreightClick(event) {
}
render() {
return (
<div className="panel panel-default">
<div className="panel-heading">
Zones
</div>
<div className="panel-body">
<div className="table-responsive">
<table className="table table-hover table-striped">
<thead>
<tr>
<th className="padding5px">ID</th>
<th className="padding5px">Fracht_ID</th>
<th className="padding5px">Land_Nr</th>
<th className="padding5px">Gebiet_von</th>
<th className="padding5px">Gebiet_bis</th>
<th className="padding5px">Suchart_Nr</th>
<th className="padding5px">Zone_Nr</th>
<th className="padding5px">Zonen</th>
</tr>
</thead>
<tbody>
{
this.state.zones.map((zone)=> {
return (
<Zone zone={zone} key={zone.id} />
);
})
}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
export default ZoneList
Zone.js:
import React, { Component } from 'react';
class Zone extends Component {
constructor(props) {
super(props);
this.state = {
zone: props.zone
};
}
render() {
return (
<tr className="cursorPointer">
<td>
<div className="checkbox">
<label>
<input type="checkbox" value="" />
</label>
</div>
</td>
<td>
{ this.state.zone.ID }
</td>
<td>
{ this.state.zone.Fracht_ID }
</td>
<td>
{ this.state.zone.Gebiet_von }
</td>
<td>
{ this.state.zone.Gebiet_bis }
</td>
<td>
{ this.state.zone.Land_Nr }
</td>
<td>
{ this.state.zone.Suchart_Nr }
</td>
<td>
{ this.state.zone.Zone_Nr }
</td>
<td>
{ this.state.zone.Zonen }
</td>
</tr>
);
}
}
export default Zone
最佳答案
当子组件使用本地 state
时,您应该在收到的每个新 prop 上更新该 state
。你可以用 componentWillReceiveProps
来做到这一点
您的评论的后续内容:
是的,每个将接收到的 props
“映射”到其本地状态的组件都应该在收到的每个新 props
上设置其状态。
我想我可以看到您感到困惑的地方,您将 props
映射到 constructor
调用中的 state
,但不要忘记,构造函数仅调用一次。
render
将在每次 state
更改时调用,但您不会更改状态,因此它不会重新:渲染它自己。
收到新 props
时更改状态的方法是使用 componentWillReceiveProps
。
话虽如此,我真的建议尽可能使用没有状态和生命周期方法的无状态组件。
我建议阅读this post作者:Cory House 关于无状态组件的好处
关于javascript - React - 为什么组件没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44691427/