小编pun*_*pun的帖子

我可以从外部组件使用useReducer吗

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

// 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;
Run Code Online (Sandbox Code Playgroud)
// ProductReducer Component
import React, { useReducer } from 'react';
import {totalDis} from './TotalReducer'
//{totalDis} is dispatch and i dont need {total}


export const [product, productDis] …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 reactjs react-hooks

5
推荐指数
2
解决办法
1118
查看次数

标签 统计

ecmascript-6 ×1

javascript ×1

react-hooks ×1

reactjs ×1