我不明白我在这里遗漏了什么,非常感谢您的帮助!
我正在通过命令 history.push (urlState) 从另一个功能组件进入我的“测试”功能组件。
"urlState" 是一个对象,我在 "Test" 组件的 useEffect 函数中检查它的值。
根据 urlState 中的值,我决定是否执行“setRequestNumber”和“setRequestSubNumber”,以及向它们发送哪些值。
但是set函数不起作用!!
我做错了什么??
(我希望 useEffect 只运行一次,所以我将依赖项数组留空。)
这是我的代码-
import React, { useState, useEffect } from "react";
import {URL} from "../../config/Constants"
const Test = (props) => {
const [requestNumber, setRequestNumber] = useState(0);
const [requestSubNumber, setRequestSubNumber] = useState(1);
const getRequestDetails = async (fetchURL) => {
try {
const response = await fetch(fetchURL);
if (!response.ok) {
throw new Error("something went wrong!");
}
const body = await response.json();
const result = body.results;
console.log(result); //result will be rendered instead of <h1>Hi there!</h1>
} catch (error) {}
};
const getNextRequestCounter = async () => {
try {
const response = await fetch(`${URL}/requests/requestCounter`);
if (!response.ok) {
throw new Error("something went wrong!");
}
const body = await response.json();
const result = body.results[0];
setRequestNumber(result);
} catch (error) {
}
};
useEffect(() => {
var urlState = {
request: 1,
subRequest: 2,
isNewRequest: false,
originalSubRequest: 1,
}; // That what I have in props.location.state;
var fetchURL = "";
if (urlState.isNewRequest) {
getNextRequestCounter();
fetchURL = `${URL}/requests/${requestNumber}/${requestSubNumber}`;
} else {
setRequestNumber(urlState.request);
setRequestSubNumber(urlState.subRequest);
fetchURL = `${URL}/requests/${requestNumber}/${urlState.originalSubRequest}`;
}
getRequestDetails(fetchURL);
}, []);
return <h1>Hi there!</h1>;
};
export default Test;
谢谢!