gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:56:25 26 4
gpt4 key购买 nike

React 中的上下文和 reducers 非常新。我目前正在尝试使用 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(...)

关于reactjs - 上下文 - 分派(dispatch)不是函数(React),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63806058/

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