react dispatch一次shouldComponentUpdate方法却输出了两次。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import intl from 'intl';
import { injectIntl, intlShape } from 'react-intl';
import { Layout, Menu, Row, Col, Modal, messa`请输入代码`ge, Spin } from 'antd';
import LoginForm from './loginForm.jsx';
import WrappedRegistrationForm from './registerForm.jsx';
import ForgetPassord from './forgetPasswordForm.jsx';
import { LOGIN, REGISTER_ASYNC } from '../../utils/events.jsx';
import { tipMessage } from '../common/tipMessage.jsx';

message.config({
    top: 60,
    duration: 2,
});
class LoginPage extends Component {
    constructor(props) {
        super(props);
   
        this.state = {
            username: '',
            password: '',
            message: '',
            showModal: false,
            showGetPassModal: false,
            isLoading: false,
            loadTimeoutID: 0,
        };

        this.handleSubmit = this.handleSubmit.bind(this);
        this.register = this.register.bind(this);
        this.handleOk = this.handleOk.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.registerSubmit = this.registerSubmit.bind(this);
        this.forgetPassword = this.forgetPassword.bind(this);
        this.handleLookOk = this.handleLookOk.bind(this);
        this.handleLookCancel = this.handleLookCancel.bind(this);
        this.forgetPasswordSubmit = this.forgetPasswordSubmit.bind(this);
        this.showLoadingPage = this.showLoadingPage.bind(this);
        this.hideLoadingPage = this.hideLoadingPage.bind(this);
    }
      shouldComponentUpdate(nextProps,nextState){
       
        console.log('shouldComponentUpdate',nextProps)
        return true;
    }
    componentWillReceiveProps(nextProps) {
        // console.log('dfdfsdf', nextProps)
        // if (nextProps.jsonData) {
        //     this.setState({ isLoading: false });
        //     const isTimeOut = this.hideLoadingPage(false);
        //     if (nextProps.jsonData.from && nextProps.jsonData.from === 'register') {
        //         if (nextProps.jsonData.status.code === 1) {
        //             tipMessage('success', this.props.intl.formatMessage({ id: 'Register_succeess' }));
        //             // this.setState({ showModal: false });
        //             return;
        //         } else if (nextProps.jsonData.status.code === 1004) {
        //             this.setState({ showModal: false });
        //             tipMessage('error', this.props.intl.formatMessage({ id: 'Register_messageRepeat' }));
        //         } else {
        //             this.setState({ showModal: false });
        //             tipMessage('error', this.props.intl.formatMessage({ id: 'Register_fial' }));
        //         }
        //         return;

        //     }

        //     if (!isTimeOut){ //如果登录未超时
        //         if (nextProps.jsonData.status.code === 1) {                
        //             const data = nextProps.jsonData.data;
        //             const token = data.token;
        //             const username = data.user_name;
        //             const menus = data.menus;
        //             const developer = data.developer;
        //             localStorage.setItem('jwtToken', token);
        //             localStorage.setItem('loggedinusername', username);
        //             localStorage.setItem('menus', JSON.stringify(menus));
        //             this.props.router.push(developer.length > 0 ? '/ProductManage' : '/DeveloperInfo');
        //         } else {
        //             message.error(this.context.intl.formatMessage({ id: 'LoginPage_errormessage' }));                
        //             this.setState({ message: nextProps.jsonData.status.msg });
        //         }
        //     }
        // }
    }
    handleSubmit(info) {
        const languages = navigator.languages;
        let currentLang = null;
        if (languages !== undefined) {
            if (languages[0] === 'en-US' || languages[0] === 'en') {
                currentLang = 'en-US';
            } else {
                currentLang = 'zh-CN';
            }
        } else {
            if (languages === 'en-US' || languages === 'en') {
                currentLang = 'en-US';
            } else {
                currentLang = 'zh-CN';
            }
        }
        info.languageid = currentLang;
        this.props.dispatch({ type: LOGIN, user: info });
        this.showLoadingPage();
    }

    registerSubmit(registerValues) {
        if (registerValues === 'cancel') {
            this.setState({ showModal: false });
            return;
        }
        console.log('注册')
        this.props.dispatch({ type: REGISTER_ASYNC, user: registerValues });
    }

    showLoadingPage(){
        const loadTimeoutID = setTimeout( () => {
            this.hideLoadingPage(true);
        }, 15000);
        this.setState({ isLoading: true, loadTimeoutID: loadTimeoutID });
    }

    hideLoadingPage(isTimeOut){
        clearTimeout(this.state.loadTimeoutID);
        this.setState({isLoading: false});
        if (isTimeOut) {
            message.error(this.props.intl.formatMessage({ id: 'LoginPage_overtimeError' }), 3);
        }
        return isTimeOut;
    }

    register() {
        this.setState({
            showModal: true
        });
    }

    forgetPassword() {
        this.setState({ showGetPassModal: true });
    }

    forgetPasswordSubmit(values) {
        if (values === 'cancel') {
            this.setState({ showGetPassModal: false });
        }
    }
    handleOk() {
        this.setState({ showModal: false });

    }
    handleCancel() {
        this.setState({ showModal: false });

    }
    handleLookCancel() {
        this.setState({ showGetPassModal: false });
    }
    handleLookOk() {
        this.setState({ showGetPassModal: false });
    }
    render() {
        const { intl } = this.props;
        const { Header, Content, Footer } = Layout;
        const { username, password } = this.state;
        return (

            <Layout className="layout-login">
                <Content className="content-login">
                    <Spin spinning={this.state.isLoading}>
                        <Row>
                            <Col span={8} offset={8} className="text-align-center">
                                <h1>
                                    {intl.formatMessage({ id: 'LoginPage_welcome' })}
                                </h1>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8} offset={8}>
                                <LoginForm intl={intl} handleSubmit={this.handleSubmit.bind(this)} register={this.register.bind(this)} forgetPassword={this.forgetPassword.bind(this)} />
                            </Col>
                        </Row>
                    </Spin>
                </Content >
                <Footer style={{ textAlign: 'center' }}>
                    iHealth Api ©2016 Created by iHealth Cloud
                </Footer>
                <Modal title={intl.formatMessage({ id: 'RegisterTitle_title' })}
                    visible={this.state.showModal}
                    onOk={this.handleOk.bind(this)}
                    onCancel={this.handleCancel.bind(this)}
                    key={Math.random()}
                    footer={null}
                    width={600}
                >
                    <WrappedRegistrationForm intl={intl} handleSubmit={this.registerSubmit.bind(this)} />
                </Modal>
                <Modal title={intl.formatMessage({ id: 'lookPassword_title' })}
                    visible={this.state.showGetPassModal}
                    onOk={this.handleLookOk.bind(this)}
                    onCancel={this.handleLookCancel.bind(this)}
                    key={Math.random()}
                    width={600}
                    footer={null}
                >
                    <ForgetPassord intl={intl} handleSubmit={this.forgetPasswordSubmit.bind(this)} />
                </Modal>

            </Layout >
        );
    }
}
LoginPage.contextTypes = {
    intl: React.PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
    jsonData: state.loginReducer.jwtToken
});
const mapDispatchToProps = (dispatch) => ({
    dispatch
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(LoginPage))

为什么dispatch一次而shouldComponentUpdate却调用了两次?各位帮帮忙!!
阅读 3.3k
2 个回答

代码太多了,看的不是特别仔细。shouldComponentUpdate只会在组件将要重新渲染的时候才会被调用,所以我大胆的猜一下,应该是接收到新props内部有多个被更新的数据。

var shallowCompare = require( 'react-addons-shallow-compare' );
shouldComponentUpdate(nextProps, nextState) {

var me = shallowCompare(this, nextProps, nextState);
console.log('scroll', me)
return me;

}

试试这个。数据不同时候,才会进行update

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题