简体   繁体   English

React 组件被调用两次

[英]React component being called twice

The Portal component is being called twice. Portal组件被调用了两次。

Why is it happening?为什么会这样?

How can I prevent that?我怎样才能防止这种情况?


index.js

const App = () => {
  const theme = lightTheme;

  return (
    <Provider store={store}>
      <StyleSheetManager>
        <ThemeProvider theme={theme}>
          <BrowserRouter>
            <Portal />
          </BrowserRouter>
          <GlobalStyle />
        </ThemeProvider>
      </StyleSheetManager>
    </Provider>
  );
};

ReactDOM.render(<App />, document.getElementById("app"));

Portal.jsx

class Portal extends React.Component {
  isAuthenticated = () => {
    if (this.props.tokenized) {
      return (
        <React.Fragment>
          <Sidebar />
          <MainContainer />
          <Switch>
            <Route exact path="/"></Route>
          </Switch>
        </React.Fragment>
      );
    } else {
      return <Authorize />;
    }
  };

  render() {
    this.props.dispatch(checkToken());
    return (
      <React.Fragment>
        <Alerts />
        {this.isAuthenticated()}
      </React.Fragment>
    );
  }
}

export default connect(
  ({ authenticator }) => ({
    tokenized: authenticator.tokenized,
  }),
  null
)(Portal);

This happens as you're dispatching an action on every render and the redux state is probably getting updated after the first dispatch call to it.当您在每个渲染上调度一个动作时,就会发生这种情况,并且 redux state 可能在第一次调度调用后得到更新。

When your Portal renders for the first time, yu dispatch checkToken() which checks for token probably and updates authenticator.tokenized .当您的Portal第一次呈现时,yu 调度checkToken()可能会检查令牌并更新authenticator.tokenized Since your component is connected to the store to map state to props, your prop tokenized carries a new value therefore causing a re-render.由于您的组件连接到存储到 map state 到道具,因此tokenized的道具带有一个新值,因此会导致重新渲染。 BUT, rendering twice of this particular component is not erronuous as the token can be only avilable after some time(after the first render of the component).但是,这个特定组件的两次渲染并不是错误的,因为令牌只能在一段时间后(在组件的第一次渲染之后)才可用。

You should memoize the component so that you can perform checks to incoming props with previous props to avoid unnecessary re-renders.您应该记住该组件,以便您可以使用以前的道具对传入的道具进行检查,以避免不必要的重新渲染。

Also, your checkToken call should happen only once when the component loads (in componentDidMount ) and not everytime in each render method execution.此外,您的 checkToken 调用应该只在组件加载时(在componentDidMount中)发生一次,而不是在每个渲染方法执行中每次都发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM