React State 没有正确分配 setState [英] React State is not assigning properly with setState

查看:49
本文介绍了React State 没有正确分配 setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个非常基本的待办事项应用程序.但是我在将待办事项推入数组并将它们分配给状态时遇到问题.

I'm creating a very basic todo app. But I'm getting an issue with pushing todos into an array and assigning them to the state.

  constructor(props){
    super(props);
    this.state = {
      todo : '',
      todos : []
    };
  };

  todoValue(todo){
    console.log(`Received the todo in the App : ${todo}`);
    this.setState({todo});
    console.log(this.state.todo);
  }

在这里,当我单击一个按钮时,我在 todoValue 函数的 todo 参数中收到 todo 值.但它不会分配给事件的状态.它确实将值分配给下一个事件的状态.

Here when I click a button I'm receiving todo value in todo argument of todoValue function. But it doesn't assign to the state on the event. It does assign the value to the state on next event.

举个例子,如果我在第一个事件中收到的待办事项值为 one,而在下一个事件中收到的待办事项值为 two,这就是我得到的.

As an example if I receive todo value as one in first event and todo value as two in next event this is what I'm getting.

我想将 todo 值分配给按钮点击时的状态(而不是下一个事件)

I want to assign the todo value to the state on the button click (not on the next event)

如何解决这个问题?

推荐答案

setState 是一个异步操作,但它确实允许在操作完成时触发回调.将您的代码更改为

this.setState({ todo }, () => console.log(this.state.todo));

您将看到您对状态所做的最新更改.

and you'll see the latest changes you made to the state.

这篇关于React State 没有正确分配 setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆