Javascript 避免在componentDidUpdate上使用setState
要求 我有一个链接列表。每个链接都有一个通过ID的唯一URL。每个链接都应该打开或更新一个窗口。任何时候都只能打开一个窗口,不能打开多个窗口 解决方案Javascript 避免在componentDidUpdate上使用setState,javascript,facebook,reactjs,redux,react-redux,Javascript,Facebook,Reactjs,Redux,React Redux,要求 我有一个链接列表。每个链接都有一个通过ID的唯一URL。每个链接都应该打开或更新一个窗口。任何时候都只能打开一个窗口,不能打开多个窗口 解决方案 import React from 'react'; let PopUp = React.createClass({ propTypes: { id: React.PropTypes.string }, getInitialState: function() { return {
import React from 'react';
let PopUp = React.createClass({
propTypes: {
id: React.PropTypes.string
},
getInitialState: function() {
return {
id: null,
popUp: null
};
},
componentDidUpdate: function() {
let url = 'http://test.com/' + this.props.id;
if(this.state.popUp) {
this.state.popUp.close();
}
this.setState({
popUp: window.open(url, '_blank'),
id: this.props.id
});
},
shouldComponentUpdate: function(nextProps, nextState) {
//If no id
if(!nextProps.id) {
return false;
}
//If same id and open window
if(nextProps.id === nextState.id && nextState.popUp && !nextState.popUp.closed) {
return false;
}
return true;
},
render: function() {
return null;
}
});
export default PopUp;
这很有效。但问题是,我必须在组件diddupdate中使用setState。这将在整个生命周期中引起另一个循环
这能避免吗?有更好的解决办法吗?我应该使用全局的还是全局的
谢谢
组件将收到道具
而不是组件更新
好主意,谢谢!