我在componentDidMount()中使用setState函数时遇到了一些问题.
我想做的是:我正在努力使HTML5圈响应(如果浏览器窗口更大则更大,反之亦然).
到目前为止我所做的事情:我一直在将这些维度存储在名为containerDim的状态中.默认情况下,此值设置为null.这是我所做的非常基本的实现:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {containerDim: null};
this.resizeCircle = this.resizeCircle.bind(this) //To not loose value of this
}
componentDidMount() {
var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height
this.setState({
containerDim: {width:dimensions.width, height: dimensions.height}
});
window.addEventListener("resize", this.resizeCircle));
}
resizeCircle() { //THE RESIZING WORKS, THE initial setting of state doesn't
var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height
this.setState({
containerDim: {width:dimensions.width, height: dimensions.height}
});
}
render() {
return (
<div ref={"responsiveContainer"} >
<Circle dimensions={this.state.containerDim} />
</div>
);
}
}
//Circle component
class Circle extends React.Component {
constructor(props) {
super(props);
}
componentWillReceiveProps() {
console.log(this.props.dimensions); //THIS LOGS OUT NULL
}
render() {
CIRCLE GOES HERE
}
}
基本上我正在尝试使用此代码来获取“responseContainer”的宽度和高度,并将其作为道具传递给< Circle />零件.
上述方法不起作用,因为setState不会改变状态.
任何帮助将不胜感激!
编辑:
这个“作品”,但我觉得它不正确,应该有更好的方法:
var dimensions = window.getComputedStyle(this.refs.container);
setTimeout(function() {
this.setState({
screenDim:{width:dimensions.width, height:dimensions.height}
});
}.bind(this),0);
this.setState({
screenDim:{width:dimensions.width, height:dimensions.height}
});
最佳答案 该组件不会在didMount中监听状态修改;这意味着即使状态更新,也不会触发重绘.