简体   繁体   English

在React中重新渲染父组件

[英]Rerender Parent Component in React

I'm learning React and TypeScript and I am trying to write a login form, but after checking the user's data and creating the cookie, I want to rerender the parent component. 我正在学习React和TypeScript,我正在尝试编写一个登录表单,但在检查用户的数据并创建cookie之后,我想要重新呈现父组件。

I have index.tsx (short version): 我有index.tsx (短版):

import React from 'react';
import ReactDOM from 'react-dom';
import cookie from 'react-cookies'

function Main() {
    let hmCookies = cookie.loadAll();
    console.log(hmCookies.auth);
    if (hmCookies.auth === 'true') {
        return (<Logout />)
    } else {
        return (<Login />)
    }
}
ReactDOM.render(<Main />, document.getElementById('root'));

and Logint.tsx : Logint.tsx

import React from 'react';
import cookie from 'react-cookies'

const axios = require('axios');
class Login extends React.Component<any, any> {
  ...
  handleSubmit(event) {
    axios.post('http://localhost/php/Login.php', {
      login: this.state.login,
      password: this.state.password
    }, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
      .then(function (response) {
        if (response.data.auth == true) {
          cookie.save('auth', true);
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    event.preventDefault();
  }
  render() { return ( <LoginFormHere /> ) }
}
export default Login;

After posting the user data in the form and making a request to PHP script via ajax, PHP returns a response. 在表单中发布用户数据并通过ajax向PHP脚本发出请求后,PHP返回响应。 If it's true, save cookie. 如果是,请保存cookie。 So, after changing cookie, I want to rerender component Main . 因此,在更改cookie之后,我想重新呈现组件Main However, I have no idea how to do this and I can't find any examples of this in the documentation. 但是,我不知道如何做到这一点,我在文档中找不到任何这方面的例子。

How can this be achieved? 怎么能实现这一目标?

You can create a function in your Main component to serve to rerender. 您可以在Main组件中创建一个函数来进行重新渲染。 Let's call it - updateParent . 我们称之为 - updateParent Then you can pass updateParent function to your Login component as props and use it if response.data.auth == true . 然后,您可以将updateParent函数作为props传递给Login组件,并在response.data.auth == true使用它。 updateParent can be implemented as in the following question . updateParent可以像下面的问题一样实现

Here the example . 这里的例子

Also, you could use a stateful(class) component instead of functional. 此外,您可以使用有状态(类)组件而不是功能组件。 This allows you to use forceUpdate 这允许您使用forceUpdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM