React Hooks状态总是落后一步

时间:2019-11-03 17:35:50

标签: reactjs react-hooks

我在React中有各种功能,我需要使用useState更改状态,然后根据新状态是否满足某些条件来执行一些操作。

当用prop =“ newpassword”调用handleChange时,它在useState中使用setValues方法设置newpassword的值。然后使用正则表达式测试对新密码进行评估,如果有效,则应将状态变量passwordIsValid设置为true。

public class PlayerController : MonoBehaviour
{

    public float forwardVelocity = 0F;
    public float maxSpeed = 180;
    public float acceleratePerSecond = 8.0F;
    public float rotateSpeed = 3.0F;
    private float yaw = 0.0f;
    private float pitch = 0.0f;
    protected Rigidbody rb;
    float timeZeroToMax = 2.5F;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        acceleratePerSecond = maxSpeed / timeZeroToMax;
        forwardVelocity = 0F;

    }

    // Update is called once per frame
    void Update()
    {

            if (Input.GetKey(KeyCode.UpArrow)) //Accelerate The Vehicle
            {
                if (forwardVelocity< maxSpeed)
                {
                forwardVelocity += acceleratePerSecond * Time.deltaTime;

                }

            }


        forwardVelocity = Mathf.Min(forwardVelocity, maxSpeed);


        rb.velocity = transform.forward * forwardVelocity;


        transform.Rotate(0, Input.GetAxis("Mouse X") * rotateSpeed, 0);


        yaw += rotateSpeed * Input.GetAxis("Mouse X");


        transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
    }

}

状态总是比tho落后一步-我知道这是因为useState是异步的,但是我不知道如何使用useEffect来检查状态?钩子很新,有人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

useState()钩子只是一个函数调用。它返回值和函数对。 values只是一个常数,没有任何属性绑定。

// Think of this line
const [values, setValues] = useState(0);

// As these two lines
const values = 0;
const setValues = someFunction;

调用setValues时,将更新下一个渲染的值。下次渲染组件时,它将再次调用useState,它将返回新值。

作为解决方案,您应该使用event.target.value。不过,您不想直接使用它,因为在观察event.target后会将其无效。

const newValue = event.target.value
// use newValue to setValues etc

答案 1 :(得分:0)

在任何特定的渲染中,道具和状态永远保持不变,并且组件渲染中的每个函数(包括事件处理程序,效果,超时或其中的API调用)都捕获定义了渲染的道具和状态。因此,如果您尝试在事件处理程序中访问values.newPassword,则始终会获得该特定渲染的状态,即旧密码。

只需将useState视为一个函数,该函数返回该特定渲染的状态,并且该状态对于该特定渲染是不可变的。