我正在构建一个应用程序,我根据代码从股票市场api获取数据。我在服务器上使用redux并在客户端上做出反应+ redux并使用sockets.io在两者之间进行通信。
我设置应用程序的方式是,最初状态只是填充了代码列表。没有从API获取关于每个股票代码的数据。在客户端,只要发出状态事件(每次新用户连接到套接字时都会发出),客户端的以下代码将调度操作
socket.on('state', state => {
store.dispatch({
type: 'SET_TICKERS',
state
});
});
现在,要从服务器端实际获取数据,我将从客户端的组件生命周期钩子内部调度操作
class StockList extends Component {
constructor(props){
super(props);
this.renderButton = this.renderButton.bind(this);
}
renderButton(stock){
return(
<button key={stock} type='button' className='btn btn-primary stock-btn'>
{stock}
<span className='glyphicon glyphicon-remove' aria-hidden='true'
onClick={() => this.props.onClick(stock)}></span>
</button>
)
}
render() {
if(this.props.stocks){
return (
<div>
{this.props.stocks.map(stock => {
return this.renderButton(stock);
})}
</div>
)
}else{
return(
<div>Loading...</div>
)
}
}
componentDidUpdate() {
console.log('The component did update');
console.log(this.props.stocks.toJS());
this.props.fillState(this.props.currentState);
}
}
我从componentDidUpdate函数内部进行调用。在使用代码列表设置状态后立即更新。但是,问题是componentDidUpdate生命周期钩子发出了太多的动作请求,导致api崩溃。为什么会这样?我是否通过从componentDidUpdate内部发送调度来创建无限循环?请问节流会解决这个问题吗?
答案 0 :(得分:1)
我认为执行this.props.fillState(this.props.currentState)
会更新父组件状态,导致父render()
方法执行,因此您的组件会收到新的道具,它会触发componentWillReceiveProps()
方法,从而导致{{1}执行,所以是的 - 你创造了某种无限循环。
要避免这种情况 - 您可以使用componentDidUpdate()
方法或更改组件树的数据流 - 我可以告诉您,如果通过道具传递shouldComponentUpdate()
对象和currentState
功能,您可以好好激活这个函数和父组件(如果你想让子组件参与这个过程,可以使用fillState
)。
我建议您详细了解react component lifecycle