gpt4 book ai didi

javascript - 我可以从外部组件使用 useReducer

转载 作者:行者123 更新时间:2023-12-03 13:29:13 26 4
gpt4 key购买 nike

现在我尝试使用 useReducer 创建一种管理状态和功能的新方法,但现在发现问题是“Hooks 只能在函数组件的主体内部调用”有什么办法可以解决这个问题吗?

// App Component
import React from "react";

import { product, productDis } from "./ProductReducer";
//{product} is state, {productDis} is dispatch

import { total } from "./TotalReducer";
//{total} is state and i dont need {totalDis}


const App = () => {
return (
<div>
<button onClick={()=>productDis({type:'add',payload:'pen'})}>add</button>
{product} {total}
</div>
);
};
export default App;
// ProductReducer Component
import React, { useReducer } from 'react';
import {totalDis} from './TotalReducer'
//{totalDis} is dispatch and i dont need {total}


export const [product, productDis] = useReducer((state, action) => {
switch (action.type) {
case "add": {
const product_0 = 'pencil'
const product_1 = `${action.payload} and ${product_0}`
totalDis({
type:'total_add',
payload:'250'
})
return product_1;
}
default:
return state;
}
}, []);
// TotalReducer Component
import React, { useReducer } from 'react';

export const [total, totalDis] = useReducer((total, action) => {
switch (action.type) {
case "total_add": {
const vat = action.payload*1.15
return vat;
}
default:
return total;
}
}, 0)

当我单击显示屏上的按钮时,应该显示...“钢笔和铅笔 287.5”

但它显示“Hooks 只能在函数组件的主体内部调用”

有什么办法可以解决这个问题吗?或者我应该回归自然?

最佳答案

React hooks 只能在功能组件内部调用。钩子(Hook)状态是按组件实例维护的。如果必须重用钩子(Hook),可以将它们提取到自定义钩子(Hook)中,这些钩子(Hook)是调用内置钩子(Hook)的函数,并且应该在功能组件内部调用:

export const useTotal = () => {
const [total, totalDis] = useReducer((total, action) => {...}, 0);
...
return [total, totalDis];
};

如果需要维护多个组件的公共(public)状态,则应将其维护在公共(public)父组件中并通过 props 提供给子组件:

const Root = () => (
const [total, totalDispatcher] = useTotal();

return <App {...{total, totalDispatcher}}/>
);

const App = props => {
return (
<div>{props.total}</div>
);
};

或者上下文API:

const TotalContext = createContext();

const Root = () => (
<TotalContext.Provider value={useTotal()}>
<App/>
</TotalContext.Provider>
);

const App = () => {
const [total] = useContext(TotalContext);
return (
<div>{total}</div>
);
};

关于javascript - 我可以从外部组件使用 useReducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55322352/

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