componentWillMount中的setState不反映在componentWillMount中

时间:2017-10-25 21:49:37

标签: javascript reactjs

我正在做一个ajax请求在我的componentWillMount函数中的react组件。我有一个状态变量。我将此变量的状态设置为ajax调用的响应。

23, 34, 22, 12                                                                                                                                                           
14, 56, 74

现在在我的componentDidMount函数中,我正在尝试console.log的state_variable值。理想情况下,我应该将state_variable的值作为我在上面设置为响应的值。但是在控制台中我看到值打印为空数组,这是state_variable的初始化值。

为什么componentDidMount现在能够获得我设置的值?我做错了什么

3 个答案:

答案 0 :(得分:2)

您的ajax调用通常位于componentDidMount中,而不是componentWillMount中。原因是您不希望在已卸载的组件中进行调用,并且您假设在组件安装之前未返回数据。

我确定一切正常,你可能只是在componentWillMount ajax调用返回之前记录。而不是这样做,做一些像:

$.ajax({
  // call parameters go here
}).then(function(response) {
  this.setState({ state_variable: response });
})

now do your logging inside of render instead:

render() {
  console.log(this.state.state_variable)
  // normal render jsx here
}

渲染将在setState调用完成后重新执行,因此您应该获得一个好的日志。

答案 1 :(得分:1)

是什么让你认为AJAX调用将在<?php require '../php/connect.php'; if(isset($_POST['login'])){ $username = mysqli_real_escape_string($con, $_POST['username']); $password = mysqli_real_escape_string($con, $_POST['password']); $stmt = mysqli_prepare($con, "SELECT * FROM users WHERE username = ? AND password = ?") $stmt->mysqli_stmt_bind_param($stmt, "ss", '$username', '$password'); mysqli_stmt_execute($stmt); $run_user = mysqli_query($con, $stmt); $check_user = mysqli_num_rows($run_user); if($check_user>0){ header('location:../dashboard.php'); }else{ header('location:/pages/loginerror.php'); } } ?> 运行时完成? componentDidMount()在第一个componentWillMount()之前立即执行,render()在第一个componentDidMount()之后立即执行。因此,在生命周期执行所需的时间内,您的AJAX调用没有足够的时间来完成和更新您的状态。

https://reactjs.org/docs/react-component.html#the-component-lifecycle

答案 2 :(得分:0)

ComponentWillMount旨在用作服务器呈现的react上的componentDidMount的等效生命周期方法。并不意味着它将首先完成。反应方式是从异步调用设置加载属性并呈现加载ui,直到请求完成。