React / Redux组件不会在状态更改时重新呈现

问题描述 投票:1回答:2

我认为这个问题已经回答了几次,但我找不到具体案例。

https://codesandbox.io/s/jjy9l3003

所以基本上我有一个App组件触发一个动作,如果屏幕调整大小并且小于500px,则触发将状态调用“isSmall”更改为true(如果它更高则返回false)

class App extends React.Component {
...
resizeHandeler(e) {
    const { window, dispatch } = this.props;
    if (window.innerWidth < 500 && !this.state.isSmall) {
      dispatch(isSmallAction(true));
      this.setState({ isSmall: true });
    } else if (window.innerWidth >= 500 && this.state.isSmall) {
      dispatch(isSmallAction(false));
      console.log(isSmallAction(false));
      this.setState({ isSmall: false })
    }
  };

  componentDidMount() {
    const { window } = this.props;
    window.addEventListener('resize', this.resizeHandeler.bind(this));
  }
...

我还有一个名为HeaderContainer的组件,它是App的子项并连接到Store并且状态为“isSmall”,我希望当“isSmall”更改状态时,此组件会重新呈现...但它不是

class Header extends React.Component {

  constructor(props) {
    super(props);

    this.isSmall = props.isSmall;
    this.isHome = props.isHome;
  }
  ...
  render() {
     return (
      <div>
        {
          this.isSmall
          ?
           (<div>Is small</div>)
          :
           (<div>is BIG</div>)
        }
      </div>
    );
   }
   ...

即使我可以通过控制台看到redux实际上正在更新存储,Header组件也不会重新渲染。有人能指出我错过了什么吗?

我误解了“connect()”redux-react功能吗?

reactjs react-redux
2个回答
1
投票

查看您发布的链接上的代码,您的组件通过connect连接到redux商店

const mapStateToProps = (state, ownProps) => {
  return {
    isHome: ownProps.isHome,
    isSmall: state.get('isSmall')
  }
}


export const HeaderContainer = connect(mapStateToProps)(Header);

这意味着您在mapStateToProps函数(isHome和isSmall)中访问的道具将从redux存储中获取并作为props传递到您的组件中。

要让React重新渲染你的组件,你必须在render函数中使用'this.props'(每当一个prop更改时调用render):

render() {
     return (
      <div>
        {
          this.props.isSmall
          ?
           (<div>Is small</div>)
          :
           (<div>is BIG</div>)
        }
      </div>
    );
   }

你在constructor中做得很好但是构造函数只在组件安装之前调用一次。你应该看一下反应生命周期方法:https://reactjs.org/docs/react-component.html#constructor

您可以在Header.js文件中完全删除constructor

您还应该避免在可能的情况下使用公共类属性(例如this.isSmall = props.isSmall;),并在组件需要时使用React本地状态:https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class


1
投票

一个组件只安装一次,然后只通过传递新的道具进行更新。因此,构造函数仅在mount之前被调用一次。这意味着您在此处设置的实例属性在安装组件的生命周期内永远不会更改。您必须在this.props函数中直接访问render()才能进行更新。您可以删除构造函数,因为在这种情况下他没有做任何有用的事情。

© www.soinside.com 2019 - 2024. All rights reserved.