两次调用componentDidMount

时间:2019-08-20 12:32:22

标签: reactjs react-redux

我有一个小型的React应用。在App.js中,我具有布局 Sidenav Content 区域。侧面导航显示在某些页面上,并被其他页面隐藏。当我使用sidenav转到某些组件时,redux会设置sidenav标志并再次呈现该组件,在 componentDidMount 中,我进行了api调用,并且执行了两次。

class App extends Component {

  renderSidebar = () => {
    const {showNav} = this.props;
    return showNav ? (
            <TwoColumns>
                <Sidenav/>
            </TwoColumns>) : null;
  };

  render() {
    const {showNav} = this.props;
    const Column = showNav ? TenColumns : FullColumn;

    return (
      <Row spacing={0}>
           {this.renderSidebar()}
           <Column>
               <Route exact path="/measurements/:id/:token/:locale/measure"
                                                component={MeasurementPage}/>
           </Column>
      </Row>
    )
  }
}


const mapStateToProps = state => ({
    showNav: state.sidenav.showNav
});

export default connect(mapStateToProps)(App);

我尝试使用 shouldComponentUpdate 阻止第二次API调用

class MeasurementPage extends Component { 
  constructor(props) {
    // This update the redux "showNav" flag and re-render the component
    props.toggleSidenav(false);
  }

  shouldComponentUpdate(nextProps) {
    return !nextProps.showNav === this.props.showNav;
  }

  componentDidMount() {
    // This is executed twice and made 2 api calls
    this.props.getMeasurement(params);
  }

  render() {
    return <h1>Some content here</h1>;
  }
}

const mapStateToProps = state => ({
    showNav: state.sidenav.showNav
});

export default connect(mapStateToProps)(MeasurementPage);

有人从这个状态更新中挣扎了吗?如何解决它?

2 个答案:

答案 0 :(得分:1)

比较应该是

  shouldComponentUpdate(nextProps) {
    return !(nextProps.showNav === this.props.showNav)
  }

问题是!nextProps.showNav取反showNav值而不是取反角色表达式值,这就是为什么需要隔离运算符的原因。

答案 1 :(得分:1)

this.setState()可能会对组件的生命周期造成副作用。我们习惯在props.toggleSidenav(false)内进行此类操作,并且由于以下原因而对其进行了折旧/删除:)。我建议您将其移至componentWillMount

componentDidMount