- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用钩子(Hook)和上下文 api。我有多个操作将它们写入单独的文件中。我的问题是:在另一个文件中如何访问状态?我使用此文件来创建我的上下文:创建上下文.js
import React, { useReducer } from "react";
export default (reducer, actions, defaultValue) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, defaultValue);
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{ state, ...boundActions }}>
{children}
</Context.Provider>
);
};
return { Context, Provider };
};
当我想创建上下文时,我将 actions、reducer 和默认值传递给 createContext 文件,并从中获取 Context 和 Provider。如下所示:产品上下文.js
import createDataContext from "./createDataContext";
import {storeProducts, detailProduct} from "../data";
const productReducer = (state, action) => {
switch (action.type) {
case "GET_ITEM":
return {...state, productDetail: action.productDetail};
case "ADD_TOTALS":
return {
...state,
cartSubTotal: action.cartSubTotal,
cartTotal: action.cartTotal,
cartTax: action.cartTax
};
case "ADD_TO_CART":
return {
...state,
products: action.tempProducts,
cart: [...state.cart, action.product]
};
default:
return state;
}
};
const getItem = (id) => {
const product = **products**.find(item => item.id === id);
return product;
}
const handleDetail = dispatch => (id) => {
const productDetail = getItem(id);
dispatch({type: "GET_ITEM", productDetail})
};
const addToCart = dispatch => (id) => {
let tempProducts = [...storeProducts];
const index = tempProducts.indexOf(getItem(id));
const product = tempProducts[index];
product.inCart = true;
product.count = 1;
const price = product.price;
product.total = price;
dispatch({
type: "ADD_TO_CART",
tempProducts,
product
});
const data = addTotals();
dispatch({
type: "ADD_TOTALS",
cartSubTotal: data.cartSubTotal,
cartTotal: data.cartTotal,
cartTax: data.cartTax
});
};
const addTotals = () => {
let subTotal = 0;
**cart**.map(item =>{ (subTotal += item.total)});
const tempTax = subTotal * 0.1;
const tax = parseFloat(tempTax.toFixed(2));
const total = subTotal + tax;
return {cartSubTotal: subTotal, cartTax: tax, cartTotal: total};
};
export const {Provider, Context} = createDataContext(
productReducer,
{
handleDetail,
},
{
products: storeProducts,
productDetail: detailProduct,
cart: [],
modalOpen: false,
modalProduct: detailProduct,
cartSubTotal: 0,
cartTax: 0,
cartTotal: 0
);
我无法访问粗体的购物车和产品。我该如何使用它们?
最佳答案
看起来您在 Action 创建器功能中做了很多工作,这作为 reducer 的一部分更有意义。例如,而不是这样:
const productReducer = (state, action) => {
switch (action.type) {
case 'GET_ITEM':
return { ...state, productDetail: action.productDetail };
default:
return state;
}
};
const getItem = (id) => {
// no access to state!
const product = products.find((item) => item.id === id);
return product;
};
const handleDetail = (dispatch) => (id) => {
const productDetail = getItem(id);
dispatch({ type: 'GET_ITEM', productDetail });
};
你可以这样做:
// action value
{ type: 'GET_ITEM', id: 1234 }
// reducer
const productReducer = (state, action) => {
switch (action.type) {
case 'GET_ITEM':
const productDetail = state.products.find(
(item) => item.id === action.id
);
return { ...state, productDetail };
default:
return state;
}
};
在 reducer 内部,您可以访问操作和状态。尝试设计您的操作,使其包含尽可能少的信息来实现您的意图。
关于javascript - 当我们使用 useReducer 时如何在操作中使用状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59239913/
为了深入研究 React Hooks,我决定尝试制作 snake 并使用 useReducer/useContext 状态管理。 现在,我被阻止在需要方向键来更改事件图 block 状态的地方。在 u
现在我尝试使用 useReducer 创建一种管理状态和功能的新方法,但现在发现问题是“Hooks 只能在函数组件的主体内部调用”有什么办法可以解决这个问题吗? // App Component im
我正在尝试创建一个可重复使用的useReducer与打字 Hook 。 这是我当前的代码: type State = { data?: T isLoading: boolean error
我正在编写一个自定义 Hook 来从 API 获取一些数据。如果可能的话,我希望返回的数据是类型安全的。这可以用泛型来完成吗? type Action = { type: 'PENDING' } |
我正在尝试创建一个可重复使用的useReducer与打字 Hook 。 这是我当前的代码: type State = { data?: T isLoading: boolean error
来自docs : [init, the 3d argument] lets you extract the logic for calculating the initial state outsid
我已经实现了一种相当简单的方法来将撤消添加到 useReducer 中,方法如下: export const stateMiddleware = reducerFunc => { return f
根据 React 文档: useReducer is usually preferable to useState when you have complex state logic that inv
我注意到在许多 useReducer 示例中,展开运算符在 reducer 中的使用方式如下: const reducer = (state, action) => { switch (actio
我想使用 React.useReducer 来更新状态。我的状态是一组对象。触发更新操作时,不仅更新所需索引中的值,而且更新所有这些值。我只想更新指定数组索引中的值。我该怎么做? 点击button1后
我有一个状态对象,其中包含一个名为 rows 的数组。该数组包含一个对象列表: {_id: "5e88ad4c5f6f7388d50b9480", stampa: "Confezione", S: 0
使用 useReducer 时是否可以使用调度功能发送多个操作? Hook react ?我尝试将一系列操作传递给它,但这会引发未处理的运行时异常。 明确地说,通常会有一个初始状态对象和一个 redu
我有这些: export type DataItemChild = { id: number; title:string; checked?: boolean; }; 请注意,子项可以在此
假设我实现了一个简单的全局加载状态,如下所示: // hooks/useLoading.js import React, { createContext, useContext, useReducer
我不仅需要在 ComponentDidMount 上使用 loadData() 从服务器获取数据,还需要在 onFiltersClear、onApplyFilters 和 方法之后使用>onPageC
如果我在使用 时需要添加一些副作用,我想知道我有哪些选择useReducer 钩。 例如,有一个 TODO-app: const initialState = {items: []}; const r
useReducer is usually preferable to useState when you have complex state logic that involves multipl
场景 我有一个返回操作的自定义 Hook 。 父组件“Container”利用自定义钩子(Hook)并将操作作为 prop 传递给子组件。 问题 当从子组件执行操作时,实际调度会发生两次。 现在,如果
我正在尝试使用新的 React useReducer API 获取一些数据,但卡在了我需要异步获取它的阶段。我只是不知道怎么办:/ 如何将数据获取放在 switch 语句中,或者这不是应该完成的方法?
这个问题在这里已经有了答案: Why is localStorage getting cleared whenever I refresh the page? (3 个答案) 关闭 5 个月前。 H
我是一名优秀的程序员,十分优秀!