状态更改时未调用React js componentDidUpdate

时间:2020-06-14 10:55:28

标签: reactjs

嗨,我是React的初学者,正在尝试构建我的第一个应用程序

login.js

import React from 'react'
import LoginForm from './loginForm'
import SignUpForm from './signUpForm'
import Home from './home'

class LoginPopUp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            signup: false,
            login: true,
            loginSuccess: false,
        }
        this.renderLogin = this.renderLogin.bind(this)
        this.renderSignUp = this.renderSignUp.bind(this)
        this.uponSuccessfulLogin = this.uponSuccessfulLogin.bind(this)
    }

    renderSignUp() {
        this.setState({signup: true, login: false})
    }

    renderLogin() {
        this.setState({signup: false, login: true})
    }

    uponSuccessfulLogin() {
        this.setState({loginSuccess: true})
    }

    render() {
        if (this.state.signup) {
            return <SignUpForm renderLogin={this.renderLogin}/>
        } else if (this.state.login) {
            return <LoginForm renderSignUp={this.renderSignUp} uponSuccessfulLogin={this.uponSuccessfulLogin}/>
        } else if (this.state.loginSuccess) {
            return <Home/>
        }
    }
}

export default LoginPopUp;

loginForm.js

import React from 'react'
import { post } from 'axios';

class LoginForm extends React.Component {

    constructor(props) {
      super(props);
      this.state ={
        username: '',
        password: '',
        loginSuccess: '',
        submit: false,
      }
      this.onUsernameChange = this.onUsernameChange.bind(this)
      this.onPasswordChange = this.onPasswordChange.bind(this)
      this.onLoginSubmitButton = this.onLoginSubmitButton.bind(this)
      this.authenticate = this.authenticate.bind(this)
      this.handleButtonClick = this.handleButtonClick.bind(this)
    }

    onUsernameChange(e) {
        this.setState({username: e.target.value})
    }

    onPasswordChange(e) {
        this.setState({password: e.target.value})
    }

    componentDidUpdate() {
        if (this.state.loginSuccess) {
            if (this.state.loginSuccess === 200) {
                this.props.uponSuccessfulLogin()
            } else {
                alert("Authentication Failed! Provide valid credentials.")
            }
        }
    }

    authenticate() {
        const url = 'http://127.0.0.1:8000/api-token-auth/';
        const formData = new FormData();
        formData.append('username', this.state.username);
        formData.append('password', this.state.password);
        const config = {
            headers: {
                'content-type': 'multipart/form-data'
            }
        }
        post(url, formData, config)
          .then(response => response.status)
          .then(status => this.setState({loginSuccess: status}))
    }

    onLoginSubmitButton() {
        this.authenticate()
    }

    handleButtonClick() {
        this.props.renderSignUp()
    }

    render() {
        if (!this.state.loginSuccess){
            return (
                <div>
                    <h1>Login</h1>
                    <form className='LoginForm' onSubmit={this.onLoginSubmitButton}>
                        <label>
                            Username:
                            <input onChange={this.onUsernameChange}/>
                        </label>
                        <br/>
                        <label>
                            Password:
                            <input type='password' onChange={this.onPasswordChange}/>
                        </label>
                        <br/>
                        <input type='submit' value='Submit'></input> 
                    </form>
                    <br/><br/><br/>
                    <span>Not a member? </span>
                    <button id="clickHere" onClick={this.handleButtonClick}>
                        Click here to SignUp
                    </button>
                </div>
            );
        }
    }
}

export default LoginForm;

发布成功后( .then(status => this.setState({loginSuccess:status})**)**)成功,我希望调用componentDidUpdate并呈现<Home/>,但是这里它不会呈现<Home/>,而是显示相同的登录页面。请帮助我了解我做错了什么。**

5 个答案:

答案 0 :(得分:2)

您需要调用Event.preventDefault()函数,以防止在提交表单时重新加载页面

onLoginSubmitButton(event) {
    event.preventDefault();
    this.authenticate();
}

Event.preventDefault()将在提交表单时禁用浏览器的默认行为。

答案 1 :(得分:0)

您需要将signup中的loginfalse都设置为uponSuccessfulLogin,以使代码达到最后else if种情况

 uponSuccessfulLogin() {
        this.setState({loginSuccess: true, signup: false, login: false})
    } 

答案 2 :(得分:0)

问题是因为您在componentDidUpdate中呼叫this.props.uponSuccessfulLogin(),其中仅loginSuccess得到更新,而login仍为true。因此,即使您在获得200后也提供了有效的凭据,仍然会看到Login页面。

在下面对父组件方法uponSuccessfulLogin进行更改

uponSuccessfulLogin() {
   this.setState(() => ({loginSuccess: true, signup: false, login: false}))
}

这样做是因为signuplogin将被设置为false,然后Home组件才可见。

如果您不想呈现任何内容,也可以在loginForm.js组件中输入return null

authenticate(e) {
   e.preventDefault();
   //..rest of the code
}

onLoginSubmitButton(e) {
   this.authenticate(e);
}

render() {
        if (!this.state.loginSuccess){
            //..rest of your code for displaying Login form
        } else return null;
    }

希望这会有所帮助。

答案 3 :(得分:0)

在更新登录成功时,请在scope = ['https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('your JSON credentials' % path, scope) service = build('drive', 'v3', credentials=credentials) folder_tree = "NAME OF THE FOLDER YOU WANT TO START YOUR SEARCH" folder_ids = {} folder_ids['NAME OF THE FOLDER YOU WANT TO START YOUR SEARCH'] = folder_id def check_for_subfolders(folder_id): new_sub_patterns = {} folders = service.files().list(q="mimeType='application/vnd.google-apps.folder' and parents in '"+folder_id+"' and trashed = false",fields="nextPageToken, files(id, name)",pageSize=400).execute() all_folders = folders.get('files', []) all_files = check_for_files(folder_id) n_files = len(all_files) n_folders = len(all_folders) old_folder_tree = folder_tree if n_folders != 0: for i,folder in enumerate(all_folders): folder_name = folder['name'] subfolder_pattern = old_folder_tree + '/'+ folder_name new_pattern = subfolder_pattern new_sub_patterns[subfolder_pattern] = folder['id'] print('New Pattern:', new_pattern) all_files = check_for_files(folder['id']) n_files =len(all_files) new_folder_tree = new_pattern if n_files != 0: for file in all_files: file_name = file['name'] new_file_tree_pattern = subfolder_pattern + "/" + file_name new_sub_patterns[new_file_tree_pattern] = file['id'] print("Files added :", file_name) else: print('No Files Found') else: all_files = check_for_files(folder_id) n_files = len(all_files) if n_files != 0: for file in all_files: file_name = file['name'] subfolders[folder_tree + '/'+file_name] = file['id'] new_file_tree_pattern = subfolder_pattern + "/" + file_name new_sub_patterns[new_file_tree_pattern] = file['id'] print("Files added :", file_name) return new_sub_patterns def check_for_files(folder_id): other_files = service.files().list(q="mimeType!='application/vnd.google-apps.folder' and parents in '"+folder_id+"' and trashed = false",fields="nextPageToken, files(id, name)",pageSize=400).execute() all_other_files = other_files.get('files', []) return all_other_files def get_folder_tree(folder_id): global folder_tree sub_folders = check_for_subfolders(folder_id) for i,sub_folder_id in enumerate(sub_folders.values()): folder_tree = list(sub_folders.keys() )[i] print('Current Folder Tree : ', folder_tree) folder_ids.update(sub_folders) print('****************************************Recursive Search Begins**********************************************') try: get_folder_tree(sub_folder_id) except: print('---------------------------------No furtherance----------------------------------------------') return folder_ids folder_ids = get_folder_tree(folder_id) 中进行尝试:

loginForm

答案 4 :(得分:0)

使用https://jsonplaceholder.typicode.com/posts的工作示例

并检查201 (created)的状态以完成测试示例

您必须防止发生默认事件

  onLoginSubmitButton(e) {
    e.preventDefault();
    this.authenticate();
  }

https://codesandbox.io/s/compassionate-leavitt-ctil9