从文档:
[init, the 3d argument] 允许您提取用于计算 reducer 之外的初始状态的逻辑。这对于稍后响应动作重置状态也很方便。
和代码:
function init(initialCount) {
return { count: initialCount };
}
function reducer(state, action) {
switch (action.type) {
...
case 'reset':
return init(action.payload);
...
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
...
}
Run Code Online (Sandbox Code Playgroud)
为什么我会在重用常量时这样做initialState?
const initialState = {
count: 5,
};
function reducer(state, action) {
switch (action.type) {
...
case 'reset':
return initialState;
...
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, …Run Code Online (Sandbox Code Playgroud) 我正在做一些需要维护应用程序级别状态(即全局状态)的事情,我正在使用反应钩子useContext和useReducer.
所以我正在做的是单击按钮,我正在设置我的上下文,然后通过在我的App.js.
我知道为什么我要使用我的数据,因为我首先将初始状态设置为 null,这就是为什么当我刷新页面时它再次设置为 null,但我的要求不是在单击按钮后我想将该数据存储为全局状态,以便我可以进一步使用它
但这不应该是我想要使我的数据全局化并且在刷新时它不应该丢失的情况
我的代码
我的上下文文件
import React, { useReducer, createContext } from "react";
const initialstate = {
someData: null
};
const MyContext = createContext({
someData: null,
click_btn: d => {}
});
const MyReducer = (state, action) => {
switch (action.type) {
case "BTNCLICKED":
return {
...state,
someData: action.payload
};
default:
return state;
}
};
const MyProvider = props => {
const [state, dispatch] = useReducer(MyReducer, initialstate);
const click_btn = d => …Run Code Online (Sandbox Code Playgroud) 问候,我在 typeStript 应用程序中实现 useReducer 时遇到了一些麻烦,我有几个错误(所有这些错误都在减速器上),但这是应用程序中最常见的一个,每次我调用调度函数时它都会跳转错误“预期有 0 个参数,但得到了 1”
这就是reducer的功能
interface Edit {
id?: number;
todo?: string;
}
type Actions =
{ type: "add"; payload: string }
| { type: "remove"; payload: number }
| { type: "done"; payload: number }
| { type: "all"; payload: Todo[] }
| { type: "edit"; payload: Edit };
const reducerFunction = (state: Todo[], actions: Actions) => {
const todoActions = {
add: [...state, { id: Date.now(), todo: actions.payload, isDone: false }],
edit: state.map((todo) => …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,我使用的是 React Hooks/Context API。现在,每当我的 Provider 组件挂载时,我都需要将从 localStorage 获取的数据分配给 initialState.carts / state.carts。如果 useEffect 支持返回对象,这是可能的。但是不能在 useEffect 中返回对象!
现在我该如何解决这个问题?
代码如下,
const initialState = {
books: books,
carts: []
};
export const Context = createContext(initialState);
export const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
if (localStorage.getItem("carts") !== null) {
const fetchedCarts = JSON.parse(localStorage.getItem("carts"));
//Here I want to assign 'fetchedCarts' array items in 'state.carts' or 'initialState.carts'
}
});Run Code Online (Sandbox Code Playgroud)
在useReducerReact 中使用钩子时,是否可以使用调度函数发送多个动作?我尝试将一系列操作传递给它,但这会引发未处理的运行时异常。
明确地说,通常会有一个初始状态对象和一个减速器,如下所示:
const initialState = { message1: null, message2: null }
const messageReducer = (state, action) => {
switch(action.type) {
case SET_MESSAGE1:
return {...state, message1: action.payload.message1}
case SET_MESSAGE2:
return {...state, message2: action.payload.message2}
default:
throw new Error("Something went wrong!")
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以像这样使用 useReducers 调度函数处理反应应用程序中的状态。
[state, dispatch] = useReducer(messageReducer, initialState)
...
dispatch({type: SET_MESSAGE1: payload: {message1: "setting message1"})
dispatch({type: SET_MESSAGE2: payload: {message2: "setting message2"})
Run Code Online (Sandbox Code Playgroud)
我想要做的是将这两个突变发送到一个数组中,这样我只需要调用一次 dispatch,就像这样:
dispatch([
{type: SET_MESSAGE1: payload: {message1: "setting message1"},
{type: SET_MESSAGE2: payload: {message2: "setting message2"}
]) …Run Code Online (Sandbox Code Playgroud) 我想在下面的代码中使用正确的 TS 类型,而不是任何类型。我是反应 TS 的新手,请帮助...
如何为以下上下文 API 代码设置 useReducer useContext 的打字稿类型:
import React, {createContext, Dispatch} from 'react';
import {firebaseUser} from '../@types/User';
interface Actions {
SET_IMAGENAME: string;
SET_USER: string;
}
export const Actions: Actions = {
SET_IMAGENAME: 'SET_IMAGENAME',
SET_USER: 'SET_USER',
};
function action(type: string) {
return {type};
}
function actionPayload(type: string, payload: any) { //here
return {type, payload};
}
export const Dispatches = {
setImageName: action,
setUser: actionPayload,
};
interface State {
imgName: string;
user: firebaseUser;
}
const initialState = { …Run Code Online (Sandbox Code Playgroud) typescript reactjs react-context react-typescript use-reducer
我的 bestSellerDummy 数据不会更改,因此我想防止在父级重新呈现时重新呈现相同的产品子级。我尝试在父级中使用 useMemo 并在子级中使用 React.memo 但没有运气,每次父级重新渲染时它仍然显示日志“渲染产品组件..”。我在这里缺少什么?请指教。
注意:每次我在 Product 组件中调用 addToCart 函数(CartContext 的)时,预计都会重新呈现父级。
我正在使用 CartContext,也许与此有关,我不确定。这是沙箱:https://codesandbox.io/s/dazzling-moore-po1c6 ?file=/src/App.js
主页.tsx
const [bestSellerDummy] = useState(
[...new Array(5)].map((item, key) => ({
id: key,
imageUri:'https://1.jpg',
name: 'My Dummy 1',
price: 25,
})),
);
const bestSellers = useMemo(() => {
return bestSellerDummy.map((productDummy, key) => {
return (
<Product key={key} product={productDummy} />
);
});
}, [bestSellerDummy]);
return (
...
{bestSellers}
...
)
Run Code Online (Sandbox Code Playgroud)
产品.tsx
const Product: FunctionComponent<IProductProps> = (
productProps,
) => {
...
console.log('Rendering Product component..');
... …Run Code Online (Sandbox Code Playgroud) 我正在努力理解useReducer与useState. 有很多争论,但对我来说,没有一个真正有意义,在这篇文章中,我试图将它们应用到一个简单的例子中。
也许我错过了一些东西,但我真的不明白为什么useReducer应该在任何地方使用 over useState. 我希望你能帮助我澄清这一点。
让我们以这个例子为例:
function CounterControls(props) {
return (
<>
<button onClick={props.increment}>increment</button>
<button onClick={props.decrement}>decrement</button>
</>
);
}
export default function App() {
const [complexState, setComplexState] = useState({ nested: { deeply: 1 } });
function increment() {
setComplexState(state => {
// do very complex logic here that depends on previous complexState
state.nested.deeply += 1;
return { ...state };
});
}
function decrement() {
setComplexState(state => { …Run Code Online (Sandbox Code Playgroud) 我只是想知道是否可以使用 useReducer,因为我在 UseEffect fetched data => State => useReducer(..., State) 中使用它
const [initialData, setInitialData] = useState({ name: 'ass' });
const [data, dispatch] = useReducer(apiReducer, initialData);
const Data2 = useFetch('/qaz')
useEffect(() => {
setInitialData(Data2)
}, [Data2])
useEffect(() => {
dispatch({ type: 'Different', payload: 'key' })
}, [initialData])
export function apiReducer(state, action) {
switch (action.type) {
case 'Different':
return { ...state, key: action.payload };
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud) 我是全新的反应。我已经正式完成用头撞墙了。我就是想不通。这是我的情况:
我正在尝试将 API 调用的结果放入表中。我已调用 API 工作并返回结果。我被困在如何使用返回的数据更新我的数组。完成后,我可以用数据填充表格(至少在逻辑上这是我的大脑告诉我的方式)。
初始表单状态设置:
const initialFormState = {
fileTypeId : '',
companyMasterId: '',
investmentCompanyId: '',
startDate: '',
endDate: '',
result: '',
fileLogs: []
}
Run Code Online (Sandbox Code Playgroud)
以上所有字段都是表单\数据库中的字段。API 调用采用这些参数来调用存储过程,该过程根据搜索参数返回结果集。fileLogs[] 是我想放置返回数据的地方。我不确定是否需要将它从这个设置中移出并使用 useState 作为一个单独的东西?
减速器初始化:
const [formState, dispatch] = useReducer (formReducer, initialFormState)
Run Code Online (Sandbox Code Playgroud)
减速机设置
formReducer.js
import actionTypes from "./actionTypes"
const formReducer = (state, action) => {
switch (action.type) {
case actionTypes.handle_input_text:
return {
//using the spread operator (…state) to copy across all the properties and values from the state object.
//then we can …Run Code Online (Sandbox Code Playgroud) use-reducer ×10
reactjs ×9
react-hooks ×8
javascript ×5
typescript ×2
memoization ×1
react-memo ×1
react-native ×1
use-context ×1
use-state ×1