dispatch不是reactjs中onClick的函数

wkyowqbh  于 2023-02-12  发布在  React
关注(0)|答案(1)|浏览(140)

我想用UseReducer钩子写上下文,但出现了一个错误:调度不是一个函数,有什么问题吗?请帮帮我
几乎是正确的,但没有工作。我想看到适当的行动,通过点击按钮,一个是增量,一个是减量,另一个是重置。
对手

import { UseCount, UseCountActions } from "./CounterProvider";

const CounterOne = () => {
  const count = UseCount();
  const dispatch = UseCountActions();
  return (
    <div>
      <h2>count is:{count}</h2>

      <button onClick={() => dispatch({ type: "add", value: 1 })}>
        Addone{" "}
      </button>
      <button onClick={() => dispatch({ type: "decrement", value: 1 })}>
        decrement
      </button>
      <button onClick={() => dispatch({ type: "reset" })}>reset</button>
    </div>
  );
};

export default CounterOne;

反向提供者

import React, { useReducer, useState } from "react";
import { useContext } from "react";

const CounterContext = React.createContext();
const CounterContextDispather = React.createContext();

const initialState = 0;

const reducer = (state, action) => {
  switch (action.type) {
    case "add":
      return state + action.value;
    case "decrement":
      return state - action.value;
    case "reset":
      return initialState;
    default:
      return state;
  }
};

const CounterProvider = ({ children }) => {
  const [count, dispatch] = useReducer(reducer, initialState);
  return (
    <CounterContext.Provider value={count}>
      <CounterContextDispather.Provider value={dispatch}>
        {children}
      </CounterContextDispather.Provider>
    </CounterContext.Provider>
  );
};

export default CounterProvider;

export const UseCount = () => useContext(CounterContext);

export const UseCountActions = () => {
  return CounterContextDispather;
};
eqfvzcg8

eqfvzcg81#

export const UseCountActions = () => {
  return useContext(CounterContextDispather);
};

有一个官方的example

相关问题