gpt4 book ai didi

javascript - 如何在 useEffect 中使用 useState,访问组件挂载时更新的 useState 值?

转载 作者:行者123 更新时间:2023-12-02 22:37:33 27 4
gpt4 key购买 nike

我正在尝试构建一个可以或不能接收查询字符串的代码。如果它收到所有查询字符串,我想执行一个函数:

  // state for query
const [query, setQuery] = useState({
periodicity: "",
stock: "",
date: moment().subtract(1, "y"),
investment: ""
});


// check if there are query strings
function useQuery() {
return new URLSearchParams(useLocation().search);
}
let qs = useQuery();
let queries = {};

// set query strings received
useEffect(() => {
if (qs.has("periodicity")) {
queries.periodicity = qs.get("periodicity");
}
if (qs.has("start_date")) {
queries.date = moment(qs.get("start_date"));
}
if (qs.has("symbol")) {
queries.stock = { value: qs.get("symbol"), label: qs.get("symbol") };
}
if (qs.has("investment")) {
queries.investment = qs.get("investment");
}
setQuery({ ...query, ...queries });
if (
query.periodicity !== "" &&
query.stock !== "" &&
query.investment !== ""
) {
simulate();
}
}, []);

初始状态查询状态。我正在做的是,在组件安装时,验证是否存在查询字符串并更改组件以匹配收到的查询字符串。

问题是,我从来没有输入最后一个 if (query.periodicity !== ""&& query.stock !== ""&& query.investment !== "")。我知道这是因为 useState 将在下一个组件安装时更新状态,并且 useEffect 仅在 useState 更新状态之前运行一次。但是如何在不进入循环的情况下修复它呢?

我无法将 query 放入 useEffect 依赖项数组中,因为如果用户填充了所有数据并且 query 状态变为已填充,我不想自动运行 simulate() 函数,因为用户需要单击一个按钮。我只想在进入此页面时收到所需的所有查询字符串时自动运行它。

提前致谢!

最佳答案

您可以在组件函数体中设置状态并在useEffect回调中检查它:

function App(props) {
const initialState = {
periodicity: "",
stock: "",
date: "2019-01-01",
investment: ""
};

let qs = useQuery();
let queries = {};

if (qs.has("periodicity")) {
queries.periodicity = qs.get("periodicity");
}
if (qs.has("start_date")) {
queries.date = qs.get("start_date");
}
if (qs.has("symbol")) {
queries.stock = { value: qs.get("symbol"), label: qs.get("symbol") };
}
if (qs.has("investment")) {
queries.investment = qs.get("investment");
}

const [query, setQuery] = useState(
receivedQueryString(queries) ? queries : initialState
);

/*
* Rest of the component implementation
*/

function receivedQueryString(query) {
return (
query.periodicity != "" && query.stock != "" && query.investment != ""
);
}

useEffect(() => {
if (receivedQueryString(query)) {
simulate();
}
});

function simulate() {
props.history.push(
`/?periodicity=${query.periodicity}&start_date=${query.date}&symbol=${
query.stock.value
}&investment=${query.investment}`
);
// calls API
}

return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}

关于javascript - 如何在 useEffect 中使用 useState,访问组件挂载时更新的 useState 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58695596/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com