这可能是一种反模式,但我使用固定数据表来显示列不断变化的表。resize函数根据状态变化调整每列的宽度。但是,我需要从收到的道具中构建状态或列。我不能从render函数更新状态。有没有更好的方法来解决这个问题呢?到目前为止,我最好的解决方案是将状态宽度生成为100,但这是暂时的。
constructor(props) {
super(props);var columnWidths ={
recordid: 40,
};
for(var i=0; i<100;i++) {
columnWidths[i]=200
}
this.state = {
columnWidths
};
this._onColumnResizeEndCallback = this._onColumnResizeEndCallback.bind(this);
}
_onColumnResizeEndCallback(newColumnWidth, columnKey) {
this.setState(({ columnWidths }) => ({
columnWidths: {
...columnWidths,
[columnKey]: newColumnWidth,
}
}));
console.log(newColumnWidth + " " + columnKey)
}
发布于 2017-03-02 00:53:35
所以很明显,我可以使用componentWillUpdate()从props更新我的react状态。ThecomponentWillReceiveProps()不会更新从api调用中提取的道具。但是,我需要在道具被拉入渲染之前更新状态。如果它们是预先填好的,这个 they 解决方案可以工作,但是当页面刷新时就不能工作了:
componentWillUpdate() {
var columnWidths = {
recordid: 40,
};
Object.keys(this.props.fields).map(key => {
columnWidths[this.props.fields[key].Order] = 200;
})
this.state = {
columnWidths
};
}
我必须在第一次渲染时添加||或符号,然后在加载道具后自动创建这些道具
width={columnWidths[field.Order]||200}
发布于 2017-08-11 11:35:17
我不确定我是否理解了你的问题,但是你可以在构造函数(Props)中初始化你的状态,然后在componentWillMount或componentDidMount中使用基于this.props的setState,也可以在componentWillReceiveProps(newProps)中使用。
因此,您似乎需要在生命周期方法componentWillMount或componnentDidMount中调用setState。
https://stackoverflow.com/questions/42544798
复制