我有一个完整的运行代码,但它有一个缺陷。它从 render() 内部调用 setState()。所以,react 会抛出反模式警告。
Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount
我的逻辑是这样的。在index.js父组件中,我有如下代码。构造函数()调用具有初始值的图(),以显示图形。用户还有一个表单来指定新值并提交表单。它使用新值再次运行 graphs() 并重新渲染图形。
import React, { Component } from 'react';
import FormComponent from './FormComponent';
import PieGraph from './PieGraph';
const initialval = '8998998998';
class Dist extends Component {
constructor() {
this.state = {
checkData: true,
theData: ''
};
this.graphs(initialval);
}
componentWillReceiveProps(nextProps) {
if (this.props.cost !== nextProps.cost) {
this.setState({
checkData: true
});
}
}
graphs(val) {
//Calls a redux action creator and goes through the redux process
this.props.init(val);
}
render() {
if (this.props.cost.length && this.state.checkData) {
const tmp = this.props.cost;
//some calculations
....
....
this.setState({
theData: tmp,
checkData: false
});
}
return (
<div>
<FormComponent onGpChange={recData => this.graphs(recData)} />
<PieGraph theData={this.state.theData} />
</div>
);
}
}
FormComponent 是一个普通的表单,带有输入字段和如下所示的提交按钮。它将回调函数发送到 Parent 组件,从而触发 graphs() 和 componentWillReceiveProps。
handleFormSubmit = (e) => {
this.props.onGpChange(this.state.value);
e.preventdefaults();
}
代码一切正常。有没有更好的方法来做到这一点?在 render() 中不做 setState ?