【问题标题】:Rerender Parent Component in React在 React 中渲染父组件
【发布时间】:2019-10-07 20:55:12
【问题描述】:

我正在学习 React 和 TypeScript,我正在尝试编写一个登录表单,但是在检查了用户的数据并创建了 cookie 之后,我想重新渲染父组件。

我有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'));

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;

在表单中发布用户数据并通过 ajax 向 PHP 脚本发出请求后,PHP 会返回响应。如果是真的,请保存 cookie。因此,在更改 cookie 后,我想重新渲染组件 Main。但是,我不知道如何执行此操作,并且在文档中找不到任何示例。

如何实现?

【问题讨论】:

  • 将回调从Main 传递给child,并根据您的情况调用此函数。此函数将在内部调用 setState。请注意,这是一个基本版本。高级版本将包括一个商店,并在响应时更新其中的数据。这会触发 Main 并更新组件

标签: javascript reactjs typescript cookies jsx


【解决方案1】:

您可以在 Main 组件中创建一个函数以用于重新渲染。让我们称之为 - updateParent。然后您可以将updateParent 函数作为props 传递给您的Login 组件,并在response.data.auth == true 时使用它。 updateParent 可以像 following question 那样实现。

Here the example.

此外,您可以使用有状态(类)组件而不是函数式组件。这允许您使用forceUpdate

【讨论】:

  • 谢谢你的例子,它工作正常。但就我而言,它不想工作。我认为这是因为我的父组件和子组件位于不同的文件中。当我尝试使用事件从孩子调用 updateParent 时 - 一切正常。但是当我尝试从我的子组件中的函数调用它时,我得到了错误:第 85 行:期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions。
  • @xak2,这个错误看起来有点像你在调用函数时忘记了括号,即updateParent而不是updateParent()
猜你喜欢
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 2017-07-23
  • 2018-01-10
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 2020-02-05
相关资源
最近更新 更多