两次调用构造函数React Component

时间:2017-12-05 00:51:01

标签: javascript reactjs constructor react-router react-redux

我的反应组件的构造函数被调用两次,但我无法弄清楚原因。我使用react-redux来存储我的应用程序的语言。我有一个函数,它根据浏览器的语言设置默认语言。 LoginPage 是第一个获取渲染的组件,因此我在其构造函数中调用了我的函数。基本上它的作用是比较和发送一个动作。当我使用redux开发人员工具检查我的状态时,我发现它已经被派遣了两次。我在构造函数中打印了虚拟数据,它也被打印了两次。

LoginPage.js

import React from 'react';
import {connect} from 'react-redux';
import {startLogin} from '../actions/auth';
import {setLanguage} from '../actions/lang';

export class LoginPage extends React.Component{

  constructor(props){
    super(props);
    this.setDefaultLanguage();
    console.log('i am constructor');
  }

  changeLanguage = (e) => {
    const lan = e.target.value;
    this.props.setLanguage(lan);
  };

  setDefaultLanguage = () => {
    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';

    if(defaultLanguage == 'es'){
      this.props.setLanguage(defaultLanguage);
    }else{
      this.props.setLanguage('en');
    }
  }

  render(){
    return(
      <div className="box-layout">
        <div className="box-layout__box">
          <h1 className="box-layout__title">Expensify</h1>
          <p>It\'s time to get your expenses under control.</p>
          <button className="button" onClick={this.props.startLogin}>Log in with google</button>
          <select className="select" onChange={this.changeLanguage}>
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>
        </div>
      </div>
    )
  };
}

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
  setLanguage: (language) => dispatch(setLanguage(language))
});

export default connect(undefined, mapDispatchToProps)( LoginPage);

App.js

import React from 'react';
import ReactDom from 'react-dom';
import {Router, Route, Switch} from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import ExpenseDashBoardPage from '../components/ExpenseDashBoardPage';
import AddExpensePage from '../components/AddExpensePage';
import EditExpensePage from '../components/EditExpensePage';
import NotFoundPage from '../components/NotFoundPage';
import LoginPage from '../components/LoginPage';
import PrivateRoute from './PrivateRoute';
import PublicRoute from './PublicRoute';

export const history = createHistory();

const AppRouter = () => (
  <Router history={history}>
    <div>
      <Switch>
        <PublicRoute path="/" component={LoginPage} exact={true} />
        <PrivateRoute path="/dashboard" component={ExpenseDashBoardPage} />
        <PrivateRoute path="/create" component={AddExpensePage} />
        <PrivateRoute path="/edit/:id" component={EditExpensePage} />
        <Route component={NotFoundPage} />
      </Switch>
    </div>

  </Router>
)

export default AppRouter;

5 个答案:

答案 0 :(得分:4)

我遇到了同样的问题,因为我在公共路线中重定向用户。所以它是两次渲染组件。如果你正在使用

history.push('/');

这将使组件呈现两次。

答案 1 :(得分:3)

首先,您不应该在构造函数中调用Redux操作或任何类型的AJAX。这些事情应该在componentDidMount()

中完成

其次,我会要求商店中的语言作为道具的一部分。如果未定义,请在componentDidMount()中致电setDefaultLanguage()

我至少会做以下几点:

export class LoginPage extends React.Component {
  componentDidMount() {
    if (!this.props.lang) {
        this.setDefaultLanguage();
    }
  }

  changeLanguage = (e) => {
    const lan = e.target.value;
    this.props.setLanguage(lan);
  };

  setDefaultLanguage = () => {
    const defaultLanguage = navigator.language || navigator.userLanguage || 'en-US';

    if(defaultLanguage == 'es'){
      this.props.setLanguage(defaultLanguage);
    }else{
      this.props.setLanguage('en');
    }
  }

  render() {
    return(
      <div className="box-layout">
        <div className="box-layout__box">
          <h1 className="box-layout__title">Expensify</h1>
          <p>It\'s time to get your expenses under control.</p>
          <button className="button" onClick={this.props.startLogin}>Log in with google</button>
          <select className="select" onChange={this.changeLanguage}>
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>
        </div>
      </div>
    )
  };
}

const mapStateToProps = state => ({
    // Assuming `steate.lang` is where you would set the language.
    lang: state.lang
});

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
  setLanguage: (language) => dispatch(setLanguage(language))
});

const mergeProps = (stateProps, dispatchProps) => ({ ...stateProps, ...dispatchProps });

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(LoginPage);

答案 2 :(得分:2)

如果您检查React Dev Tools中的内容,您会看到connect(App)以及App之类的内容,因此您的console.log将被调用两次。这是因为connect是一个更高阶的组件。

如果您将this.setDefaultLanguage()(以及您的console.log移动到构建器之外并进入componentDidMount生命周期挂钩,那么它应该可以解决您的问题。< / p>

答案 3 :(得分:1)

这两次调用了某些生命周期方法,仅适用于开发模式。

“不会在生产模式下两次调用生命周期。”

答案 4 :(得分:0)

是的。这是故意的,并在此处进行了记录。它仅在开发模式下发生。

https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects