reactjs - how to pass useState state value to useReducer initialstate
问题描述
I want to pass a value from useState state value to useReducer initialstate.
const [item, setItem] = useState([]);
const initialState = {
menuOpen: true,
promoOpen: false,
couponOpen: false,
cartOpen: false,
orderOpen: false,
orderAmount: 1,
filteredItem: item,
};
const [state, dispatch] = useReducer(reducer, initialState);
const fetchUrl = async () => {
const resp = await fetch(url);
const respData = await resp.json();
const item = respData.item;
const category = respData.category;
const promo = respData.promo;
setItem(item);
setCategory(category);
setPromo(promo);
setFilterItem(item);
};
But when I do console.log(state.filteredItem)
, I got an empty array so I assume that it didn't pass the value to the initialState. Is there a way for me to pass a useState state value to useReducer initialState value?
Thanks before
解决方案
const [item, setItem] = useState([]);
You declared your state with an empty array therefore that's what filteredItem shows. If you've set your state later on, in order to change it in the reducer I think you need to use dispatch function.
推荐阅读
- android - 尝试在 Eclipse 中生成 APK
- asp.net-core - 使用 Saml2 和 Okta 作为服务提供者的 Asp.Net Core 3 中的用户身份验证
- azure - 在 Azure Devops 的拉取请求中显示接受标准
- spring-boot - Cassandra 读取查询返回空结果使用 springframework 数据 cassandra
- javascript - 我应该使用队列系统来处理多租户系统中的 PDF 文本识别吗?
- vb.net - 加载一个包含 15 个数字的 .txt 文件,显示它们并删除重复的 VB.net
- nix - 为什么 Nix lambdas 和 ? 操作员是这样交互的吗?
- javascript - 如何在两个javascript函数之间实现一个promise?
- google-ads-api - 连接媒体文件和广告
- angular - ag-grid tooltip tooltipField 不显示所有字符,包括特殊字符