我有一个服务器端渲染react应用程序(因为我也需要Facebook Seo)。
我的应用程序的一部分需要获取window.innerWidth。
我已经搜索了很长时间,其中大多数人说您无法在服务器端找到窗口,因此您也需要在客户端进行渲染。
我不知道事情如何工作,我有componentdidmount,但我的windowWidth永远是0。
服务器渲染之后,我们的bundle.js将启动,客户端的窗口将正常工作吗?为什么仍然是0?
state = {
windowWidth: 0
}
handleResize(){
this.setState({windowWidth: window.innerWidth});
}
componentDidMount () {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
render() {
return (<div>{this.state.windowWidth}</div>)
}
问题是您附加了将新宽度设置为“调整大小”侦听器的功能,这意味着仅当调整屏幕大小时,新宽度才会添加到状态。您需要在内部设置宽度componentDidMount
,然后在安装时将其宽度设置为正确。
码:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
windowWidth: 0
};
}
handleResize = () => {
this.setState({ windowWidth: window.innerWidth });
};
componentDidMount() {
this.setState({ windowWidth: window.innerWidth });
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
render() {
return (
<div>{this.state.windowWidth && <p>{this.state.windowWidth}</p>}</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句