首页 > 解决方案 > React js-显示状态值取决于 redux props 值

问题描述

我有一个组件,在该组件中我想显示状态取决于值的props值。我总是得到一个错误,在网上找不到一个好的例子。

这是我的组件(波纹管),我想在等于this.state.msg时显示值this.props.passRecoveryEditSuccess.password_changed1

我编写了massage应该设置状态的函数,这msg取决于从减速器返回的内容。

问题是我不断得到即将到来的结果: 在此处输入图像描述

我怎么解决这个问题?

`

import React, { Component } from 'react';
import {Form, Alert, FormGroup, Col, Button, FormControl, Grid} from 'react-bootstrap';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
import Header from '../header/Header';
import { PassRecoveryEdit } from '../../actions/ajax';

class PasswordRecoveryEdit extends Component {
    constructor(props){
        super(props);
        this.state ={
            password: '',
            confirmPassword: '',
            msg: ''
        } 
    }

    componentDidUpdate(){
        if(this.props.passRecoveryEditSuccess){
            this.massage()
        }
    }
    onChange = (e) => {
       this.setState({
            [e.target.name]: e.target.value
        })  
    }


    formValidation = () => {
        let isError = false;
        const errors = {};

        if(this.state.password.length < 6){
            isError =  true;
            errors.passwordLengthError = "על הסיסמה להיות ארוכה מ 6 תווים"
          }else{
            isError =  false;
            errors.passwordLengthError = ""
          }

          if( this.state.confirmPassword !==  this.state.password){
            isError =  true;
            errors.passwordMatchError = "הסיסמאות לא תואמות"

          }else{
            isError =  false;
            errors.passwordMatchError = ""
          }

        this.setState({
            ...this.state,
            ...errors
        });
        return isError
    }

    onSubmit = (e) => {
        e.preventDefault();
        //console.log('onSubmit');
        //console.log('this.state', this.state);

        let obj = {
            password: this.state.password,
            token: this.props.match.params.token
        }
    let err = this.formValidation();
        if(!err){
            this.props.PassRecoveryEdit(obj);
        // console.log('success');
        }

    }

    massage = () => {
        if(this.props.passRecoveryEditSuccess.password_changed == 1){
            this.setState({msg: 'הסיסמה עודכנה בהצלחה '});
        }else{
            this.setState({msg: 'הסיסמה לא עודכנה בהצלחה'});
        }
    }


    render() {
        return (
            <div>
                <Header headline="הזינו סיסמה חדשה"/>
                <Grid>
                    <Form horizontal onSubmit={this.onSubmit.bind(this)}>  
                        <FormGroup>
                            <FormControl 
                                ref="password"
                                name="password"
                                id="password"
                                type="password"
                                placeholder="הקלידו את הסיסמה"
                                aria-label="הקלידו את הסיסמה"
                                onChange={this.onChange.bind(this)}
                            />    
                        </FormGroup>
                        {this.state.passwordLengthError  &&
                            <Alert variant="danger" className="text-right">
                                {this.state.passwordLengthError}
                            </Alert>    
                        }

                        <FormGroup>
                            <FormControl 
                                ref="confirmPassword"
                                name="confirmPassword"
                                id="confirmPassword"
                                type="password"
                                placeholder="הקלידו הסיסמה שנית"
                                aria-label="הקלידו הסיסמה שנית"
                                onChange={this.onChange.bind(this)}
                            />    
                        </FormGroup>
                        {this.state.passwordMatchError  &&
                            <Alert variant="danger" className="text-right">
                                {this.state.passwordMatchError}
                            </Alert>    
                        }
                        <FormGroup>
                        <Col xs={12}>
                          <Button className="full-width-btn" type="submit">שינוי סיסמה</Button>
                        </Col>
                      </FormGroup>
                    </Form>

                    {this.state.msg && 

                        <Alert variant="danger" className="text-right">

                        {this.state.msg}

                    </Alert>   
                    }
                </Grid>
            </div>
        )
    }
}

const mapStateToProps = state => {
    return{
            passRecoveryEditSuccess: state.userReducer.passRecoveryEdit
    }
}


export default connect(mapStateToProps, {PassRecoveryEdit})(PasswordRecoveryEdit)

`

标签: javascriptreactjsreduxreact-props

解决方案


您正在创建一个无限循环。componentDidUpdate()每当您的状态或道具在组件中发生变化时都会被调用。所以在第一次渲染之后,你从 redux 获得更新的道具,所以componentDidUpdate()触发器,条件通过,你调用this.massage()

然后this.massage()更新组件的状态,重新触发componentDidUpdate(),它在调用之前检查相同的条件this.massage(),因此创建了循环。

你可以做的是把prevProps参数放在里面componentDidUpdate(),并用它来创建一个更受保护的条件。

componentDidUpdate(prevProps){
    if(this.props.passRecoveryEditSuccess !== prevProps.passRecoveryEditSuccess){
        this.massage()
    }
}

有了这个,你说你只会this.massage()在属于先前渲染的道具不等于新渲染时调用。


推荐阅读