简体   繁体   English

State 未在 React Fetch 中更新 function

[英]State not updating in React Fetch function

I have a state, that is set to be either true or false in a fetch statement.我有一个 state,它在获取语句中设置为 true 或 false。 When the fetch statement is called, the state is not updated until the second time the submit button is pressed.当调用 fetch 语句时,直到第二次按下提交按钮时,state 才会更新。

It is because of that, that whenever I call an if statement right after, my code automatically navigates to my home page, thinking that the adding of a new account is successful.正因为如此,每当我紧接着调用if语句时,我的代码会自动导航到我的主页,并认为添加新帐户成功。

When I try to set the state to null or false , the ternary statement automatically fires off as well.当我尝试将 state 设置为nullfalse时,三元语句也会自动触发。

I've checked the data by console logging it, and it comes back as "false" when applicable, but still never updates the state我已经通过控制台记录检查了data ,并且在适用时返回为“false”,但仍然从不更新 state

Any insight on how to approach next?关于下一步如何处理的任何见解?

Edit: The fetch is returning a boolean编辑:提取返回 boolean

    let navigate = useNavigate();

    // Error states
    const [successfulAdd, setSuccessfulAdd] = useState(true);


    // Function
    function handleRegister(e) {
        const user = { firstName, lastName, email, password, phone, userName, isAdmin };

        if (password !== passwordConfirm) {
            setPasswordMatch(false);
        } else {
            fetch("http://localhost:8080/user/add", {
                method: "POST",
                headers: { "Content-type": "application/json" },
                body: JSON.stringify(user),
            })
                .then(response => response.json())
                .then(data => setSuccessfulAdd(data));
        }

        if (successfulAdd) {
            navigate("../home");
        }
    }
.
.
.
    return (
.
.
.
         {/* Username Checker */}
         {successfulAdd ? "" : <div class="alert alert-danger" role="alert">
              The username you've entered has been taken
         </div>}
.
.
.
)

Since Fetch API and setState are both asynchronous, you might want to put the if statement and all logic inside.then(…)由于 Fetch API 和 setState 都是异步的,您可能希望将 if 语句和所有逻辑放在里面。then(...)

fetch(…)
 .then(res => res.json())
 .then(json => … //navigate here)
 .catch(err => … //set your error state here)

First, you can set the initial state to undefined .首先,您可以将初始的 state 设置为undefined

const [successfulAdd, setSuccessfulAdd] = useState(true);

Second, add the navigate logic in then of the fetch request .其次,在获取请求的 then 中添加导航逻辑。

 .then(data => { if(data) { navigateTo("./home") } })

At last, you can check if successfulAdd is false then show the user taken message.最后,您可以检查successfulAdd是否为false ,然后显示用户获取的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM