shouldComponentUpdate将不会被调用

时间:2018-06-27 08:17:04

标签: reactjs

我希望我的Video组件不要通过在shouldComponentUpdate中返回false来重新呈现。但是shouldComponentUpdate没有被调用。

预期的行为:点击视频(clickHandler)时,将调用shouldComponentUpdate并返回false。

实际行为:点击视频(clickHandler)时,组件会重新渲染并记录“渲染组件”。

下面您可以找到我的代码:

Video.js

class Video extends Component {
  shouldComponentUpdate() {
    console.log('shouldupdate video');

    return false;
  }

  clickHandler = () => {
    if (this.props.controls) {
      this.props.toggleVideoPlayer();
    }
  }

  render() {
    console.log('render component');

    return (
      <div className={s.container} onClick={this.clickHandler}>
        <video className={s.video} ref={this.video} autoPlay loop>
          <track kind="captions" />
          <source src={this.props.mp4} type="video/mp4" />
          {this.props.ogv && <source src={this.props.ogv} type="video/ogg" />}
        </video>
      </div>
    );
  }
}

Home.js

class Home extends Component {
  componentDidMount() {
    console.log('home: component did mount');
  }

  shouldComponentUpdate() {
    console.log('home: should component update.');

    return true;
  }

  render() {
    return (
      <div>
        <Header
          image={hero}
          title="Home page"
        />

        <Video mp4="http://mirrors.standaloneinstaller.com/video-sample/jellyfish-25-mbps-hd-hevc.mp4" {...this.props} controls />
      </div>
    );
  }
}

更新:

App.js

class App extends Component {
  componentDidMount() {
    this.props.fetchPages(api.API_PAGES);
    this.props.fetchPosts(api.API_POSTS);
  }

  render() {
    return (
      <div>
        {!this.props.pages.isFetching && this.props.pages.data &&
          <div>
            <Navbar {...this.props} />

            <Layout {...this.props}>
              <Switch location={this.props.location}>
                <Route
                  path={routes.HOME}
                  exact
                  component={() => (
                    <Home
                      {...this.props}
                      page={findPage(this.props.pages, 'home')}
                    />
                  )}
                />
                <Route
                  path={routes.ABOUT}
                  component={() => (
                    <About
                      {...this.props}
                      page={findPage(this.props.pages, 'informatie')}
                    />
                  )}
                />
                <Route
                  path={routes.NEWS}
                  exact
                  component={() => (
                    <News
                      {...this.props}
                      posts={this.props.posts}
                      page={findPage(this.props.pages, 'nieuws')}
                    />
                  )}
                />
                <Route
                  component={NotFound}
                />
              </Switch>
            </Layout>
          </div>
        }
      </div>
    );
  }
}

0 个答案:

没有答案