上下文 - 分派不是函数(React)

Context - dispatch is not a function (React)

对 React 中的上下文和缩减器非常陌生。我目前正在尝试使用 Context 从折线图上的事件中获取日期字符串。我使用的折线图来自 react-chartjs-2.

我的上下文已设置并提供如下:

export const Context = createContext();

const initialState = {
  isShowCarousel: false,
  date: null,
  coin: null
};
const reducer = (state, action) => {
  switch (action.type) {
    case "GRAPH_CLICKED":
      return {
        ...state,
        isShowCarousel: true,
        date: action.payload.date,
        coin: action.payload.coin
      };
    default:
      return state;
  }
};

export default function LandingPage(props) {
  const classes = useStyles();
  const [state, dispatch] = useReducer(reducer, initialState);

提供商的设置如下:

 <div className={classNames(classes.main, classes.mainRaised)}>
      <Context.Provider
          value={{
            state,
            dispatch
          }}
        >
          <SectionCryptoPrices />
          <NewsCarousel date={state.date} coin={state.coin} />
          </Context.Provider>
        </div>   

然后我的折线图组件通过以下方式导入上下文:

import React, { useContext } from 'react';
import {Line} from 'react-chartjs-2';
import { Context } from "views/CryptoMashup/LandingPage";

function LineGraph (props) {
  const dispatch = useContext(Context);
  let coin = props.coin;
  
  const state = {
      labels: props.rowData.labels,
      datasets: [
        {
          label: 'Price movement for ' + props.coin,
          fill: true,
          lineTension: 0.1,
          backgroundColor: 'rgba(75,192,192,1)',
          borderColor: 'rgba(0,0,0,1)',
          borderWidth: 2,
          data: props.rowData.prices
        }
      ]
    }
    
    return (
    // line graph
    <div className="line-graph">
        <Line
        data={state}
        options={{
            legend:{
            display:true,
            position:'bottom'
            },
            onClick: function(evt, element) {
              if(element.length > 0) {
                let ind = element[0]._index;
                let date = element[0]._xScale.ticks[ind];
                let payload = {
                  date,
                  coin
                }
                dispatch({
                  type: "GRAPH_CLICKED",
                  payload: payload
                })
              }
            }
        }}
        />
    </div>
    );
}

export default LineGraph;

但是我得到以下信息:TypeError: dispatch is not a function

如有任何帮助,我们将不胜感激。

您正在将一个对象传递给上下文提供者,因此您需要相应地销毁它:

<Context.Provider value={{ state, dispatch }}> ...</Context.Provider>

const { state, dispatch } = useContext(Context)

// Same
const value = useContext(Context)
value.dispatch(...)