【发布时间】:2019-08-28 08:41:34
【问题描述】:
我是 react 和 redux 的新手。我有一个名为“单位”的表。从那里我想获取所有数据并在添加一行后立即显示数据。这就是为什么我调用 this.props.fetchProductUnit();在 componentDidUpdate() 中。但问题是它陷入了无限循环。它一遍又一遍地发送请求。那么那里的停止条件应该是什么。
动作
export const fetchProductUnit = () => {
return async (dispatch) => {
let units=[];
await Axios.get('http://localhost:4000/getUnit').then(response => {
dispatch({ type : 'FETCH_UNITS', payload: response.data})
}).catch(err => {
console.log(err);
})
}
}
主要组件
componentDidUpdate() {
this.props.fetchProductUnit();
}
componentDidMount() {
//this.getUnitsHandler();
this.props.fetchProductUnit();
}
const mapStateToProps = (state) =>{
return {
units: state.units
}
}
return (
<div className="col-lg-6 col-md-12 col-sm-12">
<div className="card">
<div className="card-header bg-dark text-white">
<h4 className="d-inline">Product Unit Settings</h4>
<button className="d-inline btn btn-success btn-sm float-right" data-toggle="modal"
data-target="#addUnitModal">
<i className="material-icons">add</i>
</button>
<AddUnit changeInput={this.inuptChangeHandler}
addUnit={this.postUnitHandler}
state={this.state.unitName} />
</div>
<div className="card-body">
<Units units={this.props.units}
deleteUnit={this.deleteUnitHandler}
update={this.updateUnitHandler} />
</div>
</div>
</div>
)
}
}
const mapStateToProps = (state) =>{
return {
units: state.units
}
}
export default connect(mapStateToProps, {
fetchProductUnit
})(ProductUnit);
我希望 componendDidMount 最初获取数据,每次添加数据后 componentDidUpdate 将再次获取数据。
【问题讨论】: