簡體   English   中英

我無法停止使用 componentWillReceiveProps / getDerivedStateFromProps

[英]I am not being able to stop using componentWIllReceiveProps / getDerivedStateFromProps

我是 React 的新手(實際上也是編程世界),我發現我們根本不需要使用 componentWillReceiveProps / getDerivedStateFromProps,但我有這個問題:

我有一個父組件 LoginForm,在其中我獲取我的 API 並使用它的響應來重定向(如果成功),或者在登錄失敗時顯示模態(LoginFailure 組件)。 所以然后我需要從我的父 LoginForm 傳遞給模態孩子 loginFailure 道具,它在 API 響應之后發生變化,當我的 LoginFailureComponent 已經呈現時,它就像它永遠不知道父道具改變一樣。 代碼如下,抱歉太長:

class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
          username:"",
          password:"",
          remember:false,
          redirect: false,
          loginFailure: false
        };
        this.loginUser = this.loginUser.bind(this);
        this.handleInputChange = this.handleInputChange.bind(this);
    }

//Here i change the father state according to the API response:

    async loginUser() {
        await this.props.dispatch(fetchLogin(this.state));
            if (this.props.success) { //
                this.setState({
                    redirect: true
                })    
            } else {
                this.setState({
                    loginFailure: true
                })
            } 
      }


    handleInputChange(event) {
// unimportant code
    }

     handleForm(e){
           //more unimportant code but here i call the api:
         this.loginUser()
    }

    render() { 
// WHAT I WILL BE PASSING AS PROPS:
        const loginFailure = this.state.loginFailure;
        const redirect  = this.state.redirect;

        if (redirect) {
            return <Redirect to={`/profile/${this.props.token}`}/>;
        } else {   
            return ( <div className="text-center">
                <h3 className="mb-5">Login</h3>
                <Form className="w-100" onSubmit={(e)=>{this.handleForm(e)}}> 
                {/* Username: */}
                   //user input code
                {/* Password: */}
                    //password input code
                {/* Submit Button: */}
                   //submit button code
                {/*Login Failure component, HERE I PASS THE PROP ACCORDING TO THE STATE VALUE! */}
                    <LoginFailureModal loginFailure={loginFailure}></LoginFailureModal>
                </Form>
            </div>
            )
        }   
    }    
}

這是我的子組件,現在使用 willReceiveProps:

class LoginFailureModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
          show: false, //i don't initialize with the props
          stopShowing: false //and i had to use this second state to STOP re rendering the modal every time i deleted some letter of my wrong input in the father
        }
    this.handleClose = this.handleClose.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        this.setState({ 
            show: nextProps.loginFailure 
        }) 
      }

    handleClose(){
        this.setState({
            stopShowing: true
        })
    };  

    render() {     
        if (this.state.stopShowing) {
            return null
        } else {    
            return ( 
                <div key={this.props.loginFailure}>
                <Modal show={this.state.show} onHide={this.handleClose}>
                    <Modal.Header closeButton>
                        <Modal.Title>Login Failed!</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        Check your username and password and try again
                    </Modal.Body>
                </Modal>
                </div>
            )
       } 
    }   
}

我閱讀了所有關於我們應該如何替換這些的 React 文檔,但我無法將它應用於我的案例,如果你能指導我解決這個問題,我將非常感激!

感謝社區!

您可以使用React hooks ,並像這樣處理您的 api:

// ... 
// It's like comoponentDidMount
useEffect({
   // Request api
}, []) 

// It's like componentWillReceiveProps
// If props.loginFailure was changed, React use this:
useEffect({
   // your conditions and ...
}, [props.loginFailure]) // props.loginFailure is a dependency. It's a flag to call inner code

所以感謝 Milad,我能夠實現鈎子,我的模態現在完美地工作! 這是代碼:

const LoginFailureModalHooks = (props) => {
let [show, setShow] = useState(false);

useEffect(()=>{
    setShow(show=props.loginFailure)
}, [props.loginFailure]);

const handleClose = () => setShow(false);

//Render:
if (show===true) {
    return ( 
        <div key={props.loginFailure}>
        <Modal show={show} onHide={handleClose}>
            <Modal.Header closeButton>
                <Modal.Title>Login Failed!</Modal.Title>
            </Modal.Header>
            <Modal.Body>
                Check your username and password and try again
            </Modal.Body>
        </Modal>
        </div>
    );
} else {
    return null
}          
const LoginFailureModalHooks = (props) => {
let [show, setShow] = useState(false);

useEffect(()=>{
    setShow(show=props.loginFailure)
}, [props.loginFailure]);

const handleClose = () => setShow(false);

//Render:
if (show===true) {
    return ( 
        <div key={props.loginFailure}>
        <Modal show={show} onHide={handleClose}>
            <Modal.Header closeButton>
                <Modal.Title>Login Failed!</Modal.Title>
            </Modal.Header>
            <Modal.Body>
                Check your username and password and try again
            </Modal.Body>
        </Modal>
        </div>
    );
} else {
    return null
}          
}
export default LoginFailureModalHooks ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM