reactjs 为什么useState/useEffect不起作用?

zf2sa74q  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(161)

我做了很多研究和测试,但我不明白为什么我的useState和我的re-render with useEffect没有改变。对于我的项目,我使用React + nextJs。正如你将看到的,在我的控制台中,我有一个日志告诉我“我将变成TRUE”,但值保持FALSE,我的useEffect返回:“我用这个值传递效果:错误”

// IMPORTS //
...
import React, { useEffect, useState } from "react";

//FUNCTION PART //

function ContactMe({ pageInfo }: Props) {
  const [val, setVal] =useState(false)
  
  const changeVal = () => {
    console.log("I've this :", val);
    
    if (val === false) {
      console.log("I'll become TRUE");
      setVal(true)
    } else{
      console.log("I'll become FALSE");
      setVal(false)
    }
  };
  useEffect(() => {
    return console.log("I pass on the effect with this value :", val);

  },[val])

  console.log("Value is :", val)

//JSX PART //

return (
  <div>
  ...
        <p>My value is : {val}</p>
        <button onClick={() => changeVal()}>Click here</button>
  ...
  </div>
)

提前Tx为您效劳!
有时值改变,但几秒钟后它停止工作:(这是我的真实的案例的一个例子,我试图在发送过程中交换邮件上的发送按钮到加载按钮。

fnx2tebb

fnx2tebb1#

这里有一个工件,不需要返回值。同样,函数可以压缩为一行:

import React from 'react';

function ContactMe() {
  const [val, setVal] = React.useState(false);
  React.useEffect(
    () => console.log('I pass on the effect with this value :', val),
    [val],
  );

  return (
    <div>
      <p>My value is : {val}</p>
      <button onClick={() => setVal(!val)}>Click here</button>
    </div>
  );
}

export default ContactMe;

相关问题