React 服务器端渲染 - addEventListener

React Server Side Rendering - addEventListener

我有一个服务器端渲染 React 应用程序(因为我也需要 Facebook Seo)。

我的应用程序的一部分需要获取 window.innerWidth。

我找了很久,大部分都说你在服务器端找不到window,所以你需要在客户端也做渲染.

我不确定它是如何工作的,我有 componentdidmount 但我的 windowWidth 永远是 0。

服务器渲染后,我们的 bundle.js 会启动,客户端的 window 会正常工作吗?怎么还是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>)
}

问题是您将设置新宽度的函数附加到 "resize" 侦听器,这意味着只有当您调整屏幕大小时,新宽度才会添加到状态。您需要在 componentDidMount 内设置宽度,然后您就可以在安装时获得它的宽度。

sandbox

代码:

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);